Gli strumenti personalizzati ti permettono di estendere le capacità di Claude Code con le tue funzionalità attraverso server MCP in-process, consentendo a Claude di interagire con servizi esterni, API o eseguire operazioni specializzate.

Creazione di Strumenti Personalizzati

Usa le funzioni helper createSdkMcpServer e tool per definire strumenti personalizzati type-safe:
import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-code";
import { z } from "zod";

// Crea un server SDK MCP con strumenti personalizzati
const customServer = createSdkMcpServer({
  name: "my-custom-tools",
  version: "1.0.0",
  tools: [
    tool(
      "get_weather",
      "Ottieni il meteo attuale per una località",
      {
        location: z.string().describe("Nome della città o coordinate"),
        units: z.enum(["celsius", "fahrenheit"]).default("celsius").describe("Unità di temperatura")
      },
      async (args) => {
        // Chiama l'API meteo
        const response = await fetch(
          `https://api.weather.com/v1/current?q=${args.location}&units=${args.units}`
        );
        const data = await response.json();
        
        return {
          content: [{
            type: "text",
            text: `Temperatura: ${data.temp}°\nCondizioni: ${data.conditions}\nUmidità: ${data.humidity}%`
          }]
        };
      }
    )
  ]
});

Utilizzo di Strumenti Personalizzati

Passa il server personalizzato alla funzione query tramite l’opzione mcpServers come dizionario/oggetto.
Importante: Gli strumenti MCP personalizzati richiedono la modalità di input streaming. Devi usare un generatore asincrono/iterabile per il parametro prompt - una semplice stringa non funzionerà con i server MCP.

Formato del Nome dello Strumento

Quando gli strumenti MCP vengono esposti a Claude, i loro nomi seguono un formato specifico:
  • Pattern: mcp__{server_name}__{tool_name}
  • Esempio: Uno strumento chiamato get_weather nel server my-custom-tools diventa mcp__my-custom-tools__get_weather

Configurazione degli Strumenti Consentiti

Puoi controllare quali strumenti Claude può usare tramite l’opzione allowedTools:
import { query } from "@anthropic-ai/claude-code";

// Usa gli strumenti personalizzati nella tua query con input streaming
async function* generateMessages() {
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: "Che tempo fa a San Francisco?"
    }
  };
}

for await (const message of query({
  prompt: generateMessages(),  // Usa generatore asincrono per input streaming
  options: {
    mcpServers: {
      "my-custom-tools": customServer  // Passa come oggetto/dizionario, non array
    },
    // Opzionalmente specifica quali strumenti Claude può usare
    allowedTools: [
      "mcp__my-custom-tools__get_weather",  // Consenti lo strumento meteo
      // Aggiungi altri strumenti secondo necessità
    ],
    maxTurns: 3
  }
})) {
  if (message.type === "result" && message.subtype === "success") {
    console.log(message.result);
  }
}

Esempio con Strumenti Multipli

Quando il tuo server MCP ha strumenti multipli, puoi consentirli selettivamente:
const multiToolServer = createSdkMcpServer({
  name: "utilities",
  version: "1.0.0",
  tools: [
    tool("calculate", "Esegui calcoli", { /* ... */ }, async (args) => { /* ... */ }),
    tool("translate", "Traduci testo", { /* ... */ }, async (args) => { /* ... */ }),
    tool("search_web", "Cerca nel web", { /* ... */ }, async (args) => { /* ... */ })
  ]
});

// Consenti solo strumenti specifici con input streaming
async function* generateMessages() {
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: "Calcola 5 + 3 e traduci 'ciao' in spagnolo"
    }
  };
}

for await (const message of query({
  prompt: generateMessages(),  // Usa generatore asincrono per input streaming
  options: {
    mcpServers: {
      utilities: multiToolServer
    },
    allowedTools: [
      "mcp__utilities__calculate",   // Consenti calcolatrice
      "mcp__utilities__translate",   // Consenti traduttore
      // "mcp__utilities__search_web" NON è consentito
    ]
  }
})) {
  // Elabora messaggi
}

Type Safety con Python

Il decoratore @tool supporta vari approcci di definizione dello schema per la type safety:
import { z } from "zod";

tool(
  "process_data",
  "Elabora dati strutturati con type safety",
  {
    // Lo schema Zod definisce sia la validazione runtime che i tipi TypeScript
    data: z.object({
      name: z.string(),
      age: z.number().min(0).max(150),
      email: z.string().email(),
      preferences: z.array(z.string()).optional()
    }),
    format: z.enum(["json", "csv", "xml"]).default("json")
  },
  async (args) => {
    // args è completamente tipizzato basato sullo schema
    // TypeScript sa: args.data.name è string, args.data.age è number, ecc.
    console.log(`Elaborando i dati di ${args.data.name} come ${args.format}`);
    
    // La tua logica di elaborazione qui
    return {
      content: [{
        type: "text",
        text: `Dati elaborati per ${args.data.name}`
      }]
    };
  }
)

Gestione degli Errori

Gestisci gli errori con grazia per fornire feedback significativo:
tool(
  "fetch_data",
  "Recupera dati da un'API",
  {
    endpoint: z.string().url().describe("URL dell'endpoint API")
  },
  async (args) => {
    try {
      const response = await fetch(args.endpoint);
      
      if (!response.ok) {
        return {
          content: [{
            type: "text",
            text: `Errore API: ${response.status} ${response.statusText}`
          }]
        };
      }
      
      const data = await response.json();
      return {
        content: [{
          type: "text",
          text: JSON.stringify(data, null, 2)
        }]
      };
    } catch (error) {
      return {
        content: [{
          type: "text",
          text: `Impossibile recuperare i dati: ${error.message}`
        }]
      };
    }
  }
)

Strumenti di Esempio

Strumento di Query Database

const databaseServer = createSdkMcpServer({
  name: "database-tools",
  version: "1.0.0",
  tools: [
    tool(
      "query_database",
      "Esegui una query del database",
      {
        query: z.string().describe("Query SQL da eseguire"),
        params: z.array(z.any()).optional().describe("Parametri della query")
      },
      async (args) => {
        const results = await db.query(args.query, args.params || []);
        return {
          content: [{
            type: "text",
            text: `Trovate ${results.length} righe:\n${JSON.stringify(results, null, 2)}`
          }]
        };
      }
    )
  ]
});

Strumento API Gateway

const apiGatewayServer = createSdkMcpServer({
  name: "api-gateway",
  version: "1.0.0",
  tools: [
    tool(
      "api_request",
      "Effettua richieste API autenticate a servizi esterni",
      {
        service: z.enum(["stripe", "github", "openai", "slack"]).describe("Servizio da chiamare"),
        endpoint: z.string().describe("Percorso dell'endpoint API"),
        method: z.enum(["GET", "POST", "PUT", "DELETE"]).describe("Metodo HTTP"),
        body: z.record(z.any()).optional().describe("Corpo della richiesta"),
        query: z.record(z.string()).optional().describe("Parametri di query")
      },
      async (args) => {
        const config = {
          stripe: { baseUrl: "https://api.stripe.com/v1", key: process.env.STRIPE_KEY },
          github: { baseUrl: "https://api.github.com", key: process.env.GITHUB_TOKEN },
          openai: { baseUrl: "https://api.openai.com/v1", key: process.env.OPENAI_KEY },
          slack: { baseUrl: "https://slack.com/api", key: process.env.SLACK_TOKEN }
        };
        
        const { baseUrl, key } = config[args.service];
        const url = new URL(`${baseUrl}${args.endpoint}`);
        
        if (args.query) {
          Object.entries(args.query).forEach(([k, v]) => url.searchParams.set(k, v));
        }
        
        const response = await fetch(url, {
          method: args.method,
          headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
          body: args.body ? JSON.stringify(args.body) : undefined
        });
        
        const data = await response.json();
        return {
          content: [{
            type: "text",
            text: JSON.stringify(data, null, 2)
          }]
        };
      }
    )
  ]
});

Strumento Calcolatrice

const calculatorServer = createSdkMcpServer({
  name: "calculator",
  version: "1.0.0",
  tools: [
    tool(
      "calculate",
      "Esegui calcoli matematici",
      {
        expression: z.string().describe("Espressione matematica da valutare"),
        precision: z.number().optional().default(2).describe("Precisione decimale")
      },
      async (args) => {
        try {
          // Usa una libreria di valutazione matematica sicura in produzione
          const result = eval(args.expression); // Solo esempio!
          const formatted = Number(result).toFixed(args.precision);
          
          return {
            content: [{
              type: "text",
              text: `${args.expression} = ${formatted}`
            }]
          };
        } catch (error) {
          return {
            content: [{
              type: "text",
              text: `Errore: Espressione non valida - ${error.message}`
            }]
          };
        }
      }
    ),
    tool(
      "compound_interest",
      "Calcola l'interesse composto per un investimento",
      {
        principal: z.number().positive().describe("Importo dell'investimento iniziale"),
        rate: z.number().describe("Tasso di interesse annuale (come decimale, es. 0.05 per 5%)"),
        time: z.number().positive().describe("Periodo di investimento in anni"),
        n: z.number().positive().default(12).describe("Frequenza di capitalizzazione per anno")
      },
      async (args) => {
        const amount = args.principal * Math.pow(1 + args.rate / args.n, args.n * args.time);
        const interest = amount - args.principal;
        
        return {
          content: [{
            type: "text",
            text: `Analisi dell'Investimento:\n` +
                  `Capitale: $${args.principal.toFixed(2)}\n` +
                  `Tasso: ${(args.rate * 100).toFixed(2)}%\n` +
                  `Tempo: ${args.time} anni\n` +
                  `Capitalizzazione: ${args.n} volte per anno\n\n` +
                  `Importo Finale: $${amount.toFixed(2)}\n` +
                  `Interesse Guadagnato: $${interest.toFixed(2)}\n` +
                  `Rendimento: ${((interest / args.principal) * 100).toFixed(2)}%`
          }]
        };
      }
    )
  ]
});

Documentazione Correlata