As per the MCP specification:

Enable LLMs to perform actions through your server

Tools are a powerful primitive in the Model Context Protocol (MCP) that enable servers to expose executable functionality to clients. Through tools, LLMs can interact with external systems, perform computations, and take actions in the real world.

Learn more about tools

MCP Documentation

Defining a tool

import { tool } from "@mcplug/server";

export const myTool = tool(
  "This tool performs a specific action. Provide a detailed description here to help the LLM understand how and when to use this tool effectively."
)
  .input(
    z.object({
      name: z.string().describe("The name of the person"),
      age: z.number().describe("The age of the person")
    })
  )
  .output(
    z.object({
      name: z.string().describe("The name of the person"),
      age: z.number().describe("The age of the person")
    })
  )
  .handle(async ({ input, sessionId, error }) => {
    const result = await fetch("https://api.example.com/data", {
      method: "POST",
      body: JSON.stringify({ input, sessionId })
    });

    return {
      name: result.name,
      age: result.age
    };
  });

Description

The first argument of the tool function is the description of the tool. Providing a detailed description is crucial, as it helps the LLM understand how and when to use the tool effectively.

Input and output schema

You have to define input and output schemas for your tool using zod, valibot, or arktype.

The output schema is mandatory. It generates the types for the tool to provide a better developer experience when using your MCP server.

Handle

The handle function is the core of the tool and will be called when the tool is executed.

It receives the following parameters:

  • input: The data passed to the tool whose type is inferred from the input schema.
  • error: A function to return errors
  • sessionId: The ID of the current session
  • ctx: The context of the tool execution that you can create using the createCtx function.
  • env: The environment variables of your MCP server. As defined in the .env file of your project.

You can return an error to the LLM using the error function, which will build a standard RPC error.

The sessionId identifies the current execution session and can be used to store associated data.

The handle function can return either a string or an object. You don’t need to manually format the return value according to the MCP specification - this is handled automatically by the SDK.