Tools

Learn how MCP enables AI models to perform actions through tools

Tools in MCP

Tools are one of the most powerful features in MCP, allowing AI models to take actions and interact with external systems. Think of tools as functions that the AI can call to perform tasks on your behalf - always with your approval.

Tools are designed to be model-controlled, meaning the AI model can automatically suggest and use them when appropriate (with user permission). This is different from resources, which are typically selected by the user directly.

What Are Tools?

MCP tools allow AI models to:

  • Execute commands
  • Search for information
  • Modify files
  • Call APIs
  • Interact with databases
  • Perform calculations
  • And much more!

How Tools Work

Tools follow this general workflow:

  1. Discovery: The client asks the server what tools are available
  2. Selection: The AI model decides which tool(s) to use based on the user's request
  3. Approval: The user approves or rejects the tool usage (in most client implementations)
  4. Execution: The server executes the tool with the provided parameters
  5. Response: The tool returns results that the AI can use to continue the conversation

Tool Definition Structure

Each tool is defined with:

  • Name: A unique identifier for the tool (e.g., search_files)
  • Description: A human-readable explanation of what the tool does
  • Input Schema: A JSON Schema defining the parameters the tool accepts
  • Annotations: Optional metadata about the tool's behavior and side effects

Here's what a tool definition looks like:

{
  "name": "search_files",
  "description": "Search for files matching a pattern",
  "inputSchema": {
    "type": "object",
    "properties": {
      "pattern": {
        "type": "string",
        "description": "Search pattern or regex"
      },
      "directory": {
        "type": "string",
        "description": "Directory to search in"
      }
    },
    "required": ["pattern"]
  },
  "annotations": {
    "title": "Search Files",
    "readOnlyHint": true,
    "openWorldHint": false
  }
}

Tool Annotations

Tools can include annotations that provide hints about their behavior:

  • readOnlyHint: Indicates if the tool modifies its environment (false) or just reads data (true)
  • destructiveHint: Indicates if the tool performs destructive updates (when readOnlyHint is false)
  • idempotentHint: Indicates if repeated calls with the same arguments have no additional effect
  • openWorldHint: Indicates if the tool interacts with external systems/services

These annotations help clients present tools appropriately and help users make informed decisions about tool approvals.

Example Tool Types

Here are some common categories of tools you might implement:

System Operations

  • Execute shell commands
  • Manage files and directories
  • Monitor system resources

Web and API Interactions

  • Search the web
  • Call external APIs
  • Fetch webpage content

Data Processing

  • Analyze CSV/JSON data
  • Generate charts and visualizations
  • Perform calculations

Example Implementation

import { Server } from "@modelcontextprotocol/sdk/server";
 
// Create a server with tools capability
const server = new Server({
  name: "example-server",
  version: "1.0.0"
}, {
  capabilities: {
    tools: {}
  }
});
 
// Define available tools
server.setRequestHandler("tools/list", async () => {
  return {
    tools: [
      {
        name: "calculate_sum",
        description: "Add two numbers together",
        inputSchema: {
          type: "object",
          properties: {
            a: { type: "number" },
            b: { type: "number" }
          },
          required: ["a", "b"]
        },
        annotations: {
          title: "Calculate Sum",
          readOnlyHint: true,
          openWorldHint: false
        }
      }
    ]
  };
});
 
// Handle tool execution
server.setRequestHandler("tools/call", async (request) => {
  const { name, arguments: args } = request.params;
  
  if (name === "calculate_sum") {
    const { a, b } = args;
    const sum = a + b;
    
    return {
      content: [
        {
          type: "text",
          text: `The sum of ${a} and ${b} is ${sum}.`
        }
      ]
    };
  }
  
  throw new Error(`Unknown tool: ${name}`);
});

Handling Tool Errors

When a tool encounters an error, it should report it in a structured way:

// Example of proper error handling
try {
  // Tool operation
  const result = performOperation();
  return {
    content: [
      { type: "text", text: `Operation successful: ${result}` }
    ]
  };
} catch (error) {
  return {
    isError: true,
    content: [
      { type: "text", text: `Error: ${error.message}` }
    ]
  };
}

By returning errors this way, the AI model can see and potentially handle the error appropriately (such as suggesting alternatives or asking for clarification).

Best Practices

When implementing tools in your MCP server:

  1. Clear Descriptions: Provide detailed descriptions for your tools and parameters
  2. Input Validation: Validate all inputs before executing tools
  3. Appropriate Annotations: Be accurate about side effects in your tool annotations
  4. Error Handling: Return helpful error messages when things go wrong
  5. Security First: Be careful with tools that execute code or modify systems
  6. Focus on Atomicity: Keep tools focused on specific actions
  7. Document Expected Outputs: Make it clear what results your tools will return
  8. Rate Limiting: Consider limiting how often tools can be called
  9. Logging: Log tool usage for debugging and security monitoring
  10. Timeouts: Implement proper timeouts for long-running operations

Security Considerations

When exposing tools through MCP:

  • Input Validation: Always validate and sanitize all inputs
  • Limit Permissions: Only provide tools with the minimum necessary permissions
  • Prevent Injection: Be careful with tools that execute shell commands or SQL
  • Access Control: Ensure tools only access authorized resources
  • Monitor Usage: Track and audit tool usage for unusual patterns
  • Error Sanitization: Don't expose sensitive information in error messages
  • Rate Limiting: Prevent abuse through rate limiting
  • Clean Up Resources: Ensure resources are properly managed after tool execution

Remember that tools can perform actions on your system. Only install MCP servers from trusted sources, and be careful when approving tool usage in client applications.

How is this guide?

On this page