# MCPServer
[EN] Source: https://mastra.ai/reference/tools/mcp-server

The `MCPServer` class provides the functionality to expose your existing Mastra tools and Agents as a Model Context Protocol (MCP) server. This allows any MCP client (like Cursor, Windsurf, or Claude Desktop) to connect to these capabilities and make them available to an agent.

Note that if you only need to use your tools or agents directly within your Mastra application, you don't necessarily need to create an MCP server. This API is specifically for exposing your Mastra tools and agents to _external_ MCP clients.

It supports both [stdio (subprocess) and SSE (HTTP) MCP transports](https://modelcontextprotocol.io/docs/concepts/transports).

## Constructor

To create a new `MCPServer`, you need to provide some basic information about your server, the tools it will offer, and optionally, any agents you want to expose as tools.

```typescript
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { createTool } from "@mastra/core/tools";
import { MCPServer } from "@mastra/mcp";
import { z } from "zod";
import { dataProcessingWorkflow } from "../workflows/dataProcessingWorkflow";

const myAgent = new Agent({
  name: "MyExampleAgent",
  description: "A generalist to help with basic questions."
  instructions: "You are a helpful assistant.",
  model: openai("gpt-4o-mini"),
});

const weatherTool = createTool({
  id: "getWeather",
  description: "Gets the current weather for a location.",
  inputSchema: z.object({ location: z.string() }),
  execute: async ({ context }) => `Weather in ${context.location} is sunny.`,
});

const server = new MCPServer({
  name: "My Custom Server",
  version: "1.0.0",
  tools: { weatherTool },
  agents: { myAgent }, // this agent will become tool "ask_myAgent"
  workflows: {
    dataProcessingWorkflow, // this workflow will become tool "run_dataProcessingWorkflow"
  }
});
```

### Configuration Properties

The constructor accepts an `MCPServerConfig` object with the following properties:

<PropertiesTable
  content={[
    {
      name: "name",
      type: "string",
      isOptional: false,
      description:
        "A descriptive name for your server (e.g., 'My Weather and Agent Server').",
    },
    {
      name: "version",
      type: "string",
      isOptional: false,
      description: "The semantic version of your server (e.g., '1.0.0').",
    },
    {
      name: "tools",
      type: "ToolsInput",
      isOptional: false,
      description:
        "An object where keys are tool names and values are Mastra tool definitions (created with `createTool` or Vercel AI SDK). These tools will be directly exposed.",
    },
    {
      name: "agents",
      type: "Record<string, Agent>",
      isOptional: true,
      description:
        "An object where keys are agent identifiers and values are Mastra Agent instances. Each agent will be automatically converted into a tool named `ask_<agentIdentifier>`. The agent **must** have a non-empty `description` string property defined in its constructor configuration. This description will be used in the tool's description. If an agent's description is missing or empty, an error will be thrown during MCPServer initialization.",
    },
    {
      name: "workflows",
      type: "Record<string, Workflow>",
      isOptional: true,
      description:
        "An object where keys are workflow identifiers and values are Mastra Workflow instances. Each workflow is converted into a tool named `run_<workflowKey>`. The workflow's `inputSchema` becomes the tool's input schema. The workflow **must** have a non-empty `description` string property, which is used for the tool's description. If a workflow's description is missing or empty, an error will be thrown. The tool executes the workflow by calling `workflow.createRunAsync()` followed by `run.start({ inputData: <tool_input> })`. If a tool name derived from an agent or workflow (e.g., `ask_myAgent` or `run_myWorkflow`) collides with an explicitly defined tool name or another derived name, the explicitly defined tool takes precedence, and a warning is logged. Agents/workflows leading to subsequent collisions are skipped.",
    },
    {
      name: "id",
      type: "string",
      isOptional: true,
      description:
        "Optional unique identifier for the server. If not provided, a UUID will be generated. This ID is considered final and cannot be changed by Mastra if provided.",
    },
    {
      name: "description",
      type: "string",
      isOptional: true,
      description: "Optional description of what the MCP server does.",
    },
    {
      name: "repository",
      type: "Repository", // { url: string; source: string; id: string; }
      isOptional: true,
      description:
        "Optional repository information for the server's source code.",
    },
    {
      name: "releaseDate",
      type: "string", // ISO 8601
      isOptional: true,
      description:
        "Optional release date of this server version (ISO 8601 string). Defaults to the time of instantiation if not provided.",
    },
    {
      name: "isLatest",
      type: "boolean",
      isOptional: true,
      description:
        "Optional flag indicating if this is the latest version. Defaults to true if not provided.",
    },
    {
      name: "packageCanonical",
      type: "'npm' | 'docker' | 'pypi' | 'crates' | string",
      isOptional: true,
      description:
        "Optional canonical packaging format if the server is distributed as a package (e.g., 'npm', 'docker').",
    },
    {
      name: "packages",
      type: "PackageInfo[]",
      isOptional: true,
      description: "Optional list of installable packages for this server.",
    },
    {
      name: "remotes",
      type: "RemoteInfo[]",
      isOptional: true,
      description: "Optional list of remote access points for this server.",
    },
    {
      name: "resources",
      type: "MCPServerResources",
      isOptional: true,
      description:
        "An object defining how the server should handle MCP resources. See Resource Handling section for details.",
    },
    {
      name: "prompts",
      type: "MCPServerPrompts",
      isOptional: true,
      description:
        "An object defining how the server should handle MCP prompts. See Prompt Handling section for details.",
    },
  ]}
/>

## Exposing Agents as Tools

A powerful feature of `MCPServer` is its ability to automatically expose your Mastra Agents as callable tools. When you provide agents in the `agents` property of the configuration:

- **Tool Naming**: Each agent is converted into a tool named `ask_<agentKey>`, where `<agentKey>` is the key you used for that agent in the `agents` object. For instance, if you configure `agents: { myAgentKey: myAgentInstance }`, a tool named `ask_myAgentKey` will be created.

- **Tool Functionality**:
  - **Description**: The generated tool's description will be in the format: "Ask agent `<AgentName>` a question. Original agent instructions: `<agent description>`".
  - **Input**: The tool expects a single object argument with a `message` property (string): `{ message: "Your question for the agent" }`.
  - **Execution**: When this tool is called, it invokes the `generate()` method of the corresponding agent, passing the provided `query`.
  - **Output**: The direct result from the agent's `generate()` method is returned as the output of the tool.

- **Name Collisions**: If an explicit tool defined in the `tools` configuration has the same name as an agent-derived tool (e.g., you have a tool named `ask_myAgentKey` and also an agent with the key `myAgentKey`), the _explicitly defined tool will take precedence_. The agent will not be converted into a tool in this conflicting case, and a warning will be logged.

This makes it straightforward to allow MCP clients to interact with your agents using natural language queries, just like any other tool.

### Agent-to-Tool Conversion

When you provide agents in the `agents` configuration property, `MCPServer` will automatically create a corresponding tool for each agent. The tool will be named `ask_<agentIdentifier>`, where `<agentIdentifier>` is the key you used in the `agents` object.

The description for this generated tool will be: "Ask agent `<agent.name>` a question. Agent description: `<agent.description>`".

**Important**: For an agent to be converted into a tool, it **must** have a non-empty `description` string property set in its configuration when it was instantiated (e.g., `new Agent({ name: 'myAgent', description: 'This agent does X.', ... })`). If an agent is passed to `MCPServer` with a missing or empty `description`, an error will be thrown when the `MCPServer` is instantiated, and server setup will fail.

This allows you to quickly expose the generative capabilities of your agents through the MCP, enabling clients to "ask" your agents questions directly.

## Methods

These are the functions you can call on an `MCPServer` instance to control its behavior and get information.

### startStdio()

Use this method to start the server so it communicates using standard input and output (stdio). This is typical when running the server as a command-line program.

```typescript
async startStdio(): Promise<void>
```

Here's how you would start the server using stdio:

```typescript
const server = new MCPServer({
  // example configuration above
});
await server.startStdio();
```

### startSSE()

This method helps you integrate the MCP server with an existing web server to use Server-Sent Events (SSE) for communication. You'll call this from your web server's code when it receives a request for the SSE or message paths.

```typescript
async startSSE({
  url,
  ssePath,
  messagePath,
  req,
  res,
}: {
  url: URL;
  ssePath: string;
  messagePath: string;
  req: any;
  res: any;
}): Promise<void>
```

Here's an example of how you might use `startSSE` within an HTTP server request handler. In this example an MCP client could connect to your MCP server at `http://localhost:1234/sse`:

```typescript
import http from "http";

const httpServer = http.createServer(async (req, res) => {
  await server.startSSE({
    url: new URL(req.url || "", `http://localhost:1234`),
    ssePath: "/sse",
    messagePath: "/message",
    req,
    res,
  });
});

httpServer.listen(PORT, () => {
  console.log(`HTTP server listening on port ${PORT}`);
});
```

Here are the details for the values needed by the `startSSE` method:

<PropertiesTable
  content={[
    {
      name: "url",
      type: "URL",
      description: "The web address the user is requesting.",
    },
    {
      name: "ssePath",
      type: "string",
      description:
        "The specific part of the URL where clients will connect for SSE (e.g., '/sse').",
    },
    {
      name: "messagePath",
      type: "string",
      description:
        "The specific part of the URL where clients will send messages (e.g., '/message').",
    },
    {
      name: "req",
      type: "any",
      description: "The incoming request object from your web server.",
    },
    {
      name: "res",
      type: "any",
      description:
        "The response object from your web server, used to send data back.",
    },
  ]}
/>

### startHonoSSE()

This method helps you integrate the MCP server with an existing web server to use Server-Sent Events (SSE) for communication. You'll call this from your web server's code when it receives a request for the SSE or message paths.

```typescript
async startHonoSSE({
  url,
  ssePath,
  messagePath,
  req,
  res,
}: {
  url: URL;
  ssePath: string;
  messagePath: string;
  req: any;
  res: any;
}): Promise<void>
```

Here's an example of how you might use `startHonoSSE` within an HTTP server request handler. In this example an MCP client could connect to your MCP server at `http://localhost:1234/hono-sse`:

```typescript
import http from "http";

const httpServer = http.createServer(async (req, res) => {
  await server.startHonoSSE({
    url: new URL(req.url || "", `http://localhost:1234`),
    ssePath: "/hono-sse",
    messagePath: "/message",
    req,
    res,
  });
});

httpServer.listen(PORT, () => {
  console.log(`HTTP server listening on port ${PORT}`);
});
```

Here are the details for the values needed by the `startHonoSSE` method:

<PropertiesTable
  content={[
    {
      name: "url",
      type: "URL",
      description: "The web address the user is requesting.",
    },
    {
      name: "ssePath",
      type: "string",
      description:
        "The specific part of the URL where clients will connect for SSE (e.g., '/hono-sse').",
    },
    {
      name: "messagePath",
      type: "string",
      description:
        "The specific part of the URL where clients will send messages (e.g., '/message').",
    },
    {
      name: "req",
      type: "any",
      description: "The incoming request object from your web server.",
    },
    {
      name: "res",
      type: "any",
      description:
        "The response object from your web server, used to send data back.",
    },
  ]}
/>

### startHTTP()

This method helps you integrate the MCP server with an existing web server to use streamable HTTP for communication. You'll call this from your web server's code when it receives HTTP requests.

```typescript
async startHTTP({
  url,
  httpPath,
  req,
  res,
  options = { sessionIdGenerator: () => randomUUID() },
}: {
  url: URL;
  httpPath: string;
  req: http.IncomingMessage;
  res: http.ServerResponse<http.IncomingMessage>;
  options?: StreamableHTTPServerTransportOptions;
}): Promise<void>
```

Here's an example of how you might use `startHTTP` within an HTTP server request handler. In this example an MCP client could connect to your MCP server at `http://localhost:1234/http`:

```typescript
import http from "http";

const httpServer = http.createServer(async (req, res) => {
  await server.startHTTP({
    url: new URL(req.url || "", "http://localhost:1234"),
    httpPath: `/mcp`,
    req,
    res,
    options: {
      sessionIdGenerator: undefined,
    },
  });
});

httpServer.listen(PORT, () => {
  console.log(`HTTP server listening on port ${PORT}`);
});
```

Here are the details for the values needed by the `startHTTP` method:

<PropertiesTable
  content={[
    {
      name: "url",
      type: "URL",
      description: "The web address the user is requesting.",
    },
    {
      name: "httpPath",
      type: "string",
      description:
        "The specific part of the URL where the MCP server will handle HTTP requests (e.g., '/mcp').",
    },
    {
      name: "req",
      type: "http.IncomingMessage",
      description: "The incoming request object from your web server.",
    },
    {
      name: "res",
      type: "http.ServerResponse",
      description:
        "The response object from your web server, used to send data back.",
    },
    {
      name: "options",
      type: "StreamableHTTPServerTransportOptions",
      description:
        "Optional configuration for the HTTP transport. See the options table below for more details.",
      optional: true,
    },
  ]}
/>

The `StreamableHTTPServerTransportOptions` object allows you to customize the behavior of the HTTP transport. Here are the available options:

<PropertiesTable
  content={[
    {
      name: "sessionIdGenerator",
      type: "(() => string) | undefined",
      description:
        "A function that generates a unique session ID. This should be a cryptographically secure, globally unique string. Return `undefined` to disable session management.",
    },
    {
      name: "onsessioninitialized",
      type: "(sessionId: string) => void",
      description:
        "A callback that is invoked when a new session is initialized. This is useful for tracking active MCP sessions.",
      optional: true,
    },
    {
      name: "enableJsonResponse",
      type: "boolean",
      description:
        "If `true`, the server will return plain JSON responses instead of using Server-Sent Events (SSE) for streaming. Defaults to `false`.",
      optional: true,
    },
    {
      name: "eventStore",
      type: "EventStore",
      description:
        "An event store for message resumability. Providing this enables clients to reconnect and resume message streams.",
      optional: true,
    },
  ]}
/>

### close()

This method closes the server and releases all resources.

```typescript
async close(): Promise<void>
```

### getServerInfo()

This method gives you a look at the server's basic information.

```typescript
getServerInfo(): ServerInfo
```

### getServerDetail()

This method gives you a detailed look at the server's information.

```typescript
getServerDetail(): ServerDetail
```

### getToolListInfo()

This method gives you a look at the tools that were set up when you created the server. It's a read-only list, useful for debugging purposes.

```typescript
getToolListInfo(): ToolListInfo
```

### getToolInfo()

This method gives you detailed information about a specific tool.

```typescript
getToolInfo(toolName: string): ToolInfo
```

### executeTool()

This method executes a specific tool and returns the result.

```typescript
executeTool(toolName: string, input: any): Promise<any>
```

### getStdioTransport()

If you started the server with `startStdio()`, you can use this to get the object that manages the stdio communication. This is mostly for checking things internally or for testing.

```typescript
getStdioTransport(): StdioServerTransport | undefined
```

### getSseTransport()

If you started the server with `startSSE()`, you can use this to get the object that manages the SSE communication. Like `getStdioTransport`, this is mainly for internal checks or testing.

```typescript
getSseTransport(): SSEServerTransport | undefined
```

### getSseHonoTransport()

If you started the server with `startHonoSSE()`, you can use this to get the object that manages the SSE communication. Like `getSseTransport`, this is mainly for internal checks or testing.

```typescript
getSseHonoTransport(): SSETransport | undefined
```

### getStreamableHTTPTransport()

If you started the server with `startHTTP()`, you can use this to get the object that manages the HTTP communication. Like `getSseTransport`, this is mainly for internal checks or testing.

```typescript
getStreamableHTTPTransport(): StreamableHTTPServerTransport | undefined
```

### tools()

Executes a specific tool provided by this MCP server.

```typescript
async executeTool(
  toolId: string,
  args: any,
  executionContext?: { messages?: any[]; toolCallId?: string },
): Promise<any>
```

<PropertiesTable
  content={[
    {
      name: "toolId",
      type: "string",
      description: "The ID/name of the tool to execute.",
    },
    {
      name: "args",
      type: "any",
      description: "The arguments to pass to the tool\'s execute function.",
    },
    {
      name: "executionContext",
      type: "object",
      isOptional: true,
      description:
        "Optional context for the tool execution, like messages or a toolCallId.",
    },
  ]}
/>

## Resource Handling

### What are MCP Resources?

Resources are a core primitive in the Model Context Protocol (MCP) that allow servers to expose data and content that can be read by clients and used as context for LLM interactions. They represent any kind of data that an MCP server wants to make available, such as:

- File contents
- Database records
- API responses
- Live system data
- Screenshots and images
- Log files

Resources are identified by unique URIs (e.g., `file:///home/user/documents/report.pdf`, `postgres://database/customers/schema`) and can contain either text (UTF-8 encoded) or binary data (base64 encoded).

Clients can discover resources through:

1.  **Direct resources**: Servers expose a list of concrete resources via a `resources/list` endpoint.
2.  **Resource templates**: For dynamic resources, servers can expose URI templates (RFC 6570) that clients use to construct resource URIs.

To read a resource, clients make a `resources/read` request with the URI. Servers can also notify clients about changes to the resource list (`notifications/resources/list_changed`) or updates to specific resource content (`notifications/resources/updated`) if a client has subscribed to that resource.

For more detailed information, refer to the [official MCP documentation on Resources](https://modelcontextprotocol.io/docs/concepts/resources).

### `MCPServerResources` Type

The `resources` option takes an object of type `MCPServerResources`. This type defines the callbacks your server will use to handle resource requests:

```typescript
export type MCPServerResources = {
  // Callback to list available resources
  listResources: () => Promise<Resource[]>;

  // Callback to get the content of a specific resource
  getResourceContent: ({
    uri,
  }: {
    uri: string;
  }) => Promise<MCPServerResourceContent | MCPServerResourceContent[]>;

  // Optional callback to list available resource templates
  resourceTemplates?: () => Promise<ResourceTemplate[]>;
};

export type MCPServerResourceContent = { text?: string } | { blob?: string };
```

Example:

```typescript
import { MCPServer } from "@mastra/mcp";
import type {
  MCPServerResourceContent,
  Resource,
  ResourceTemplate,
} from "@mastra/mcp";

// Resources/resource templates will generally be dynamically fetched.
const myResources: Resource[] = [
  { uri: "file://data/123.txt", name: "Data File", mimeType: "text/plain" },
];

const myResourceContents: Record<string, MCPServerResourceContent> = {
  "file://data.txt/123": { text: "This is the content of the data file." },
};

const myResourceTemplates: ResourceTemplate[] = [
  {
    uriTemplate: "file://data/{id}",
    name: "Data File",
    description: "A file containing data.",
    mimeType: "text/plain",
  },
];

const myResourceHandlers: MCPServerResources = {
  listResources: async () => myResources,
  getResourceContent: async ({ uri }) => {
    if (myResourceContents[uri]) {
      return myResourceContents[uri];
    }
    throw new Error(`Resource content not found for ${uri}`);
  },
  resourceTemplates: async () => myResourceTemplates,
};

const serverWithResources = new MCPServer({
  name: "Resourceful Server",
  version: "1.0.0",
  tools: {
    /* ... your tools ... */
  },
  resources: myResourceHandlers,
});
```

### Notifying Clients of Resource Changes

If the available resources or their content change, your server can notify connected clients that are subscribed to the specific resource.

#### `server.resources.notifyUpdated({ uri: string })`

Call this method when the content of a specific resource (identified by its `uri`) has been updated. If any clients are subscribed to this URI, they will receive a `notifications/resources/updated` message.

```typescript
async server.resources.notifyUpdated({ uri: string }): Promise<void>
```

Example:

```typescript
// After updating the content of 'file://data.txt'
await serverWithResources.resources.notifyUpdated({ uri: "file://data.txt" });
```

#### `server.resources.notifyListChanged()`

Call this method when the overall list of available resources has changed (e.g., a resource was added or removed). This will send a `notifications/resources/list_changed` message to clients, prompting them to re-fetch the list of resources.

```typescript
async server.resources.notifyListChanged(): Promise<void>
```

Example:

```typescript
// After adding a new resource to the list managed by 'myResourceHandlers.listResources'
await serverWithResources.resources.notifyListChanged();
```

## Prompt Handling

### What are MCP Prompts?

Prompts are reusable templates or workflows that MCP servers expose to clients. They can accept arguments, include resource context, support versioning, and be used to standardize LLM interactions.

Prompts are identified by a unique name (and optional version) and can be dynamic or static.

### `MCPServerPrompts` Type

The `prompts` option takes an object of type `MCPServerPrompts`. This type defines the callbacks your server will use to handle prompt requests:

```typescript
export type MCPServerPrompts = {
  // Callback to list available prompts
  listPrompts: () => Promise<Prompt[]>;

  // Callback to get the messages/content for a specific prompt
  getPromptMessages?: ({
    name,
    version,
    args,
  }: {
    name: string;
    version?: string;
    args?: any;
  }) => Promise<{ prompt: Prompt; messages: PromptMessage[] }>;
};
```

Example:

```typescript
import { MCPServer } from "@mastra/mcp";
import type { Prompt, PromptMessage, MCPServerPrompts } from "@mastra/mcp";

const prompts: Prompt[] = [
  {
    name: "analyze-code",
    description: "Analyze code for improvements",
    version: "v1",
  },
  {
    name: "analyze-code",
    description: "Analyze code for improvements (new logic)",
    version: "v2",
  },
];

const myPromptHandlers: MCPServerPrompts = {
  listPrompts: async () => prompts,
  getPromptMessages: async ({ name, version, args }) => {
    if (name === "analyze-code") {
      if (version === "v2") {
        const prompt = prompts.find(
          (p) => p.name === name && p.version === "v2",
        );
        if (!prompt) throw new Error("Prompt version not found");
        return {
          prompt,
          messages: [
            {
              role: "user",
              content: {
                type: "text",
                text: `Analyze this code with the new logic: ${args.code}`,
              },
            },
          ],
        };
      }
      // Default or v1
      const prompt = prompts.find((p) => p.name === name && p.version === "v1");
      if (!prompt) throw new Error("Prompt version not found");
      return {
        prompt,
        messages: [
          {
            role: "user",
            content: { type: "text", text: `Analyze this code: ${args.code}` },
          },
        ],
      };
    }
    throw new Error("Prompt not found");
  },
};

const serverWithPrompts = new MCPServer({
  name: "Promptful Server",
  version: "1.0.0",
  tools: {
    /* ... */
  },
  prompts: myPromptHandlers,
});
```

### Notifying Clients of Prompt Changes

If the available prompts change, your server can notify connected clients:

#### `server.prompts.notifyListChanged()`

Call this method when the overall list of available prompts has changed (e.g., a prompt was added or removed). This will send a `notifications/prompts/list_changed` message to clients, prompting them to re-fetch the list of prompts.

```typescript
await serverWithPrompts.prompts.notifyListChanged();
```

### Best Practices for Prompt Handling

- Use clear, descriptive prompt names and descriptions.
- Validate all required arguments in `getPromptMessages`.
- Include a `version` field if you expect to make breaking changes.
- Use the `version` parameter to select the correct prompt logic.
- Notify clients when prompt lists change.
- Handle errors with informative messages.
- Document argument expectations and available versions.

---

## Examples

For practical examples of setting up and publishing an MCPServer, see [Publishing an MCP Server](/docs/mcp/publishing-mcp-server).

The example at the beginning of this page also demonstrates how to instantiate `MCPServer` with both tools and agents.

## Elicitation

### What is Elicitation?

Elicitation is a feature in the Model Context Protocol (MCP) that allows servers to request structured information from users. This enables interactive workflows where servers can collect additional data dynamically.

The `MCPServer` class automatically includes elicitation capabilities. Tools receive an `options` parameter in their `execute` function that includes an `elicitation.sendRequest()` method for requesting user input.

### Tool Execution Signature

When tools are executed within an MCP server context, they receive an additional `options` parameter:

```typescript
execute: async ({ context }, options) => {
  // context contains the tool's input parameters
  // options contains server capabilities like elicitation and authentication info

  // Access authentication information (when available)
  if (options.extra?.authInfo) {
    console.log("Authenticated request from:", options.extra.authInfo.clientId);
  }

  // Use elicitation capabilities
  const result = await options.elicitation.sendRequest({
    message: "Please provide information",
    requestedSchema: {
      /* schema */
    },
  });

  return result;
};
```

### How Elicitation Works

A common use case is during tool execution. When a tool needs user input, it can use the elicitation functionality provided through the tool's execution options:

1. The tool calls `options.elicitation.sendRequest()` with a message and schema
2. The request is sent to the connected MCP client
3. The client presents the request to the user (via UI, command line, etc.)
4. The user provides input, declines, or cancels the request
5. The client sends the response back to the server
6. The tool receives the response and continues execution

### Using Elicitation in Tools

Here's an example of a tool that uses elicitation to collect user contact information:

```typescript
import { MCPServer } from "@mastra/mcp";
import { createTool } from "@mastra/core/tools";
import { z } from "zod";

const server = new MCPServer({
  name: "Interactive Server",
  version: "1.0.0",
  tools: {
    collectContactInfo: createTool({
      id: "collectContactInfo",
      description: "Collects user contact information through elicitation",
      inputSchema: z.object({
        reason: z
          .string()
          .optional()
          .describe("Reason for collecting contact info"),
      }),
      execute: async ({ context }, options) => {
        const { reason } = context;

        // Log session info if available
        console.log("Request from session:", options.extra?.sessionId);

        try {
          // Request user input via elicitation
          const result = await options.elicitation.sendRequest({
            message: reason
              ? `Please provide your contact information. ${reason}`
              : "Please provide your contact information",
            requestedSchema: {
              type: "object",
              properties: {
                name: {
                  type: "string",
                  title: "Full Name",
                  description: "Your full name",
                },
                email: {
                  type: "string",
                  title: "Email Address",
                  description: "Your email address",
                  format: "email",
                },
                phone: {
                  type: "string",
                  title: "Phone Number",
                  description: "Your phone number (optional)",
                },
              },
              required: ["name", "email"],
            },
          });

          // Handle the user's response
          if (result.action === "accept") {
            return `Contact information collected: ${JSON.stringify(result.content, null, 2)}`;
          } else if (result.action === "decline") {
            return "Contact information collection was declined by the user.";
          } else {
            return "Contact information collection was cancelled by the user.";
          }
        } catch (error) {
          return `Error collecting contact information: ${error}`;
        }
      },
    }),
  },
});
```

### Elicitation Request Schema

The `requestedSchema` must be a flat object with primitive properties only. Supported types include:

- **String**: `{ type: 'string', title: 'Display Name', description: 'Help text' }`
- **Number**: `{ type: 'number', minimum: 0, maximum: 100 }`
- **Boolean**: `{ type: 'boolean', default: false }`
- **Enum**: `{ type: 'string', enum: ['option1', 'option2'] }`

Example schema:

```typescript
{
  type: 'object',
  properties: {
    name: {
      type: 'string',
      title: 'Full Name',
      description: 'Your complete name',
    },
    age: {
      type: 'number',
      title: 'Age',
      minimum: 18,
      maximum: 120,
    },
    newsletter: {
      type: 'boolean',
      title: 'Subscribe to Newsletter',
      default: false,
    },
  },
  required: ['name'],
}
```

### Response Actions

Users can respond to elicitation requests in three ways:

1. **Accept** (`action: 'accept'`): User provided data and confirmed submission
   - Contains `content` field with the submitted data
2. **Decline** (`action: 'decline'`): User explicitly declined to provide information
   - No content field
3. **Cancel** (`action: 'cancel'`): User dismissed the request without deciding
   - No content field

Tools should handle all three response types appropriately.

### Security Considerations

- **Never request sensitive information** like passwords, SSNs, or credit card numbers
- Validate all user input against the provided schema
- Handle declining and cancellation gracefully
- Provide clear reasons for data collection
- Respect user privacy and preferences

### Tool Execution API

The elicitation functionality is available through the `options` parameter in tool execution:

```typescript
// Within a tool's execute function
execute: async ({ context }, options) => {
  // Use elicitation for user input
  const result = await options.elicitation.sendRequest({
    message: string,           // Message to display to user
    requestedSchema: object    // JSON schema defining expected response structure
  }): Promise<ElicitResult>

  // Access authentication info if needed
  if (options.extra?.authInfo) {
    // Use options.extra.authInfo.token, etc.
  }
}
```

Note that elicitation is **session-aware** when using HTTP-based transports (SSE or HTTP). This means that when multiple clients are connected to the same server, elicitation requests are routed to the correct client session that initiated the tool execution.

The `ElicitResult` type:

```typescript
type ElicitResult = {
  action: "accept" | "decline" | "cancel";
  content?: any; // Only present when action is 'accept'
};
```

## Authentication Context

Tools can access request metadata via `options.extra` when using HTTP-based transports:

```typescript
execute: async ({ context }, options) => {
  if (!options.extra?.authInfo?.token) {
    return "Authentication required";
  }

  // Use the auth token
  const response = await fetch("/api/data", {
    headers: { Authorization: `Bearer ${options.extra.authInfo.token}` },
    signal: options.extra.signal,
  });

  return response.json();
};
```

The `extra` object contains:

- `authInfo`: Authentication info (when provided by server middleware)
- `sessionId`: Session identifier
- `signal`: AbortSignal for cancellation
- `sendNotification`/`sendRequest`: MCP protocol functions

> Note: To enable authentication, your HTTP server needs middleware that populates `req.auth` before calling `server.startHTTP()`. For example:
>
> ```typescript
> httpServer.createServer((req, res) => {
>   // Add auth middleware
>   req.auth = validateAuthToken(req.headers.authorization);
>
>   // Then pass to MCP server
>   await server.startHTTP({ url, httpPath, req, res });
> });
> ```

## Related Information

- For connecting to MCP servers in Mastra, see the [MCPClient documentation](./mcp-client).
- For more about the Model Context Protocol, see the [@modelcontextprotocol/sdk documentation](https://github.com/modelcontextprotocol/typescript-sdk).


---
title: "Reference: createVectorQueryTool() | Tools & MCP"
description: Documentation for the Vector Query Tool in Mastra, which facilitates semantic search over vector stores with filtering and reranking capabilities.
---

import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";