Crear herramientas MCP
Resumen
Sección titulada «Resumen»Crea herramientas MCP personalizadas para ampliar las capacidades de tu trabajador digital con integraciones externas, lógica personalizada y acceso a datos.
Crear una herramienta
Sección titulada «Crear una herramienta»-
Definir la interfaz WIT
wit/tool.wit package greentic:my-tool;interface tool {record input {query: string,options: option<string>,}record output {success: bool,data: option<string>,error: option<string>,}execute: func(input: input) -> output;}world my-tool {export tool;} -
Implementar en Rust
src/lib.rs use wit_bindgen::generate;generate!({world: "my-tool",path: "wit",});struct MyTool;impl tool::Guest for MyTool {fn execute(input: tool::Input) -> tool::Output {// Your tool logic herelet result = process_query(&input.query);tool::Output {success: true,data: Some(result),error: None,}}}fn process_query(query: &str) -> String {format!("Processed: {}", query)}export!(MyTool); -
Compilar el componente WASM
Ventana de terminal cargo build --target wasm32-wasip2 --release -
Crear el manifiesto de la herramienta
tool.yaml name: my_toolversion: "1.0.0"description: My custom MCP toolparameters:- name: querytype: stringdescription: The query to processrequired: true- name: optionstype: stringdescription: Optional configurationrequired: falsereturns:type: objectproperties:success:type: booleandata:type: stringerror:type: stringcapabilities:- network:outbound -
Registrar la herramienta
greentic.demo.yaml mcp:tools:- name: my_toolcomponent: "tools/my-tool.wasm"manifest: "tools/my-tool.yaml"
Ejemplos de herramientas
Sección titulada «Ejemplos de herramientas»Herramienta de solicitud HTTP
Sección titulada «Herramienta de solicitud HTTP»impl tool::Guest for HttpTool { fn execute(input: tool::Input) -> tool::Output { let url = &input.url; let method = input.method.unwrap_or("GET".to_string());
match http_request(&method, url, input.body.as_deref()) { Ok(response) => tool::Output { success: true, data: Some(response), error: None, }, Err(e) => tool::Output { success: false, data: None, error: Some(e.to_string()), }, } }}Herramienta de consulta a base de datos
Sección titulada «Herramienta de consulta a base de datos»impl tool::Guest for DbTool { fn execute(input: tool::Input) -> tool::Output { // Get connection string from secrets let conn_str = get_secret("database_url")?;
// Execute query (pseudo-code) let results = db_query(&conn_str, &input.query)?;
tool::Output { success: true, data: Some(serde_json::to_string(&results)?), error: None, } }}Herramienta de correo electrónico
Sección titulada «Herramienta de correo electrónico»impl tool::Guest for EmailTool { fn execute(input: tool::Input) -> tool::Output { let api_key = get_secret("sendgrid_api_key")?;
let result = send_email( &api_key, &input.to, &input.subject, &input.body, );
match result { Ok(_) => tool::Output { success: true, data: Some("Email sent".to_string()), error: None, }, Err(e) => tool::Output { success: false, data: None, error: Some(e.to_string()), }, } }}Uso de herramientas en flows
Sección titulada «Uso de herramientas en flows»Invocación directa
Sección titulada «Invocación directa»- id: call_tool type: mcp-tool config: tool: "my_tool" parameters: query: "{{user_query}}" output: tool_resultCon agente LLM
Sección titulada «Con agente LLM»- id: agent type: llm config: model: "gpt-4" system_prompt: | You are an assistant with access to tools. Use tools when needed to help the user. tools: - my_tool - http_request - send_email tool_choice: "auto"Probar herramientas
Sección titulada «Probar herramientas»Prueba unitaria
Sección titulada «Prueba unitaria»#[cfg(test)]mod tests { use super::*;
#[test] fn test_execute() { let input = tool::Input { query: "test".to_string(), options: None, };
let output = MyTool::execute(input);
assert!(output.success); assert!(output.data.is_some()); }}Prueba de integración
Sección titulada «Prueba de integración»# Test with sample inputecho '{"query": "test"}' | greentic-mcp test ./my-tool.wasmBuenas prácticas
Sección titulada «Buenas prácticas»- Maneja todos los errores - Nunca hagas panic, siempre devuelve el error en la salida
- Valida la entrada - Verifica los parámetros antes de procesarlos
- Usa secrets - Nunca hardcodees credenciales
- Agrega logging - Ayuda con la depuración
- Documenta a fondo - Descripciones claras en el manifiesto
- Prueba casos límite - Maneja entradas vacías, datos grandes, etc.