AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

mcp-builder

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

Original source
anthropics
License
Apache-2.0
Pinned revision
ca45fc496a3436251f191354091d557da31c15b5

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

This skill also requires local files or dependencies. Remote reading alone may not be enough.

Ask your assistant

Use Agentic Memory skills to read anthropics--mcp-builder at revision ca45fc496a3436251f191354091d557da31c15b5, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 7

reference/node_mcp_server_v2.md · 24000

void nodeHandler(req, res, req.body));


- `expectedResource` accepts only tokens issued for this server, so a token meant for another service is refused
- The verified `AuthInfo` reaches the factory as `createMcpHandler(({ authInfo }) => ...)` and tool handlers as `ctx.http?.authInfo` (undefined on stdio)
- Serving OAuth discovery metadata and per-tool scopes are covered by the [oauth](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/oauth) and [scoped-tools](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/scoped-tools) examples and the [authorization docs](https://ts.sdk.modelcontextprotocol.io/v2/serving/authorization.md)

**Transport selection:** stdio for local tools a host launches as a subprocess; Streamable HTTP for remote services and multiple clients.

---

## Resources and Prompts

Resources expose read-only data at a URI that the client application reads and attaches as context. Prompts are message templates a user invokes by name. Tools are for anything the model should call, including operations with side effects.

```typescript
import { completable, ProtocolError, ProtocolErrorCode, ResourceNotFoundError, ResourceTemplate } from "@modelcontextprotocol/server";

// A resource at a fixed URI
server.registerResource(
  "example-teams",
  "example://teams",
  { title: "Teams", description: "Every team in the Example workspace", mimeType: "application/json" },
  async (uri, ctx) => {
    const teams = await apiRequest<unknown>("teams", {}, ctx.mcpReq.signal);
    return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(teams) }] };
  }
);

// A URI template: the matched variables arrive as the second argument
server.registerResource(
  "example-user",
  new ResourceTemplate("example://users/{userId}", { list: undefined }),
  { title: "User profile", description: "One Example user by ID", mimeType: "application/json" },
  async (uri, { userId }, ctx) => {
    if (!/^U\d+$/.test(String(userId))) {
      throw new ProtocolError(ProtocolErrorCode.InvalidParams, `User IDs look like U123, got "${userId}"`);
    }
    const user = await apiRequest<unknown>(`users/${userId}`, {}, ctx.mcpReq.signal).catch((error: unknown) => {
      // Only a 404 means the resource is missing; a 401, 429, or timeout keeps its own error
      if (error instanceof ApiError && error.status === 404) throw new ResourceNotFoundError(uri.href);
      throw error;
    });
    return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(user) }] };
  }
);

// A prompt; completable() lets clients autocomplete the argument as the user types
const TEAMS = ["engineering", "marketing", "sales"];

server.registerPrompt(
  "example_team_report",
  {
    title: "Team report",
    description: "Summarize who is on a team",
    argsSchema: z.object({
      team: completable(z.string().describe("Team name"), value => TEAMS.filter(team => team.startsWith(value)))
    })
  },
  async ({ team }) => ({
    messages: [
      {
        role: "user",
        content: { type: "text", text: `Use example_search_users to find everyone on the ${team} team, then summarize the team in a short table.` }
      }
    ]
  })
);
  • Give a template a list callback that returns { resources: [...] } to make its instances appear in resources/list; { list: undefined } leaves them readable but unlisted
  • If a template variable becomes a filesystem path, resolve it with realpath and reject anything outside your root before reading

Notifications

The handles returned by registerTool, registerResource, and registerPrompt send the matching list_changed notification when you change them:

const exportTool = server.registerTool(
  "example_export_data",
  { description: "Export workspace data (export-enabled plans only)" },
  async () => ({ content: [{ type: "text", text: "Export started" }] })
);
exportTool.disable(); // Sends notifications/tools/list_changed
exportTool.enable(); // So do enable(), update(), and remove()

Behind createMcpHandler each request has its own server instance, so publish changes through the handler instead: handler.notify.toolsChanged(), handler.notify.resourcesChanged(). Send notifications only when the server's capabilities actually change.


Verify Your Server

Write a self-check script that starts the built server, calls its tools as a client would, and exits non-zero on any failure. Run it after every change, along with npm run build; adapt the tool names and assertions to your server.

/**
 * Self-check: starts the built server over stdio, calls its tools, and exits non-zero on any failure.
 * Run with: npm run build && npm run smoke
 */
import { strict as assert } from "node:assert";
import { Client } from "@modelcontextprotocol/client";
import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotocol/client/stdio";

const client = new Client({ name: "smoke-test", version: "1.0.0" });
await client.connect(
  new StdioClientTransport({
    command: "node",
    args: ["dist/index.js"],
    // The child gets only a safe default environment; pass the server's own variables explicitly
    env: { ...getDefaultEnvironment(), EXAMPLE_API_KEY: process.env.EXAMPLE_API_KEY ?? "" }
  })
);

const { tools } = await client.listTools();
assert.deepEqual(tools.map(tool => tool.name).sort(), ["example_get_user", "example_search_users"]);

const search = await client.callTool({
  name: "example_search_users",
  arguments: { query: "john", limit: 5, response_format: "json" }
});
assert.ok(!search.isError, `search failed: ${JSON.stringify(search.content)}`);
const page = search.structuredContent as { users: { id: string }[]; total: number };
assert.ok(Array.isArray(page.users), "search should return a users array");

if (page.users.length > 0) {
  const user = await client.callTool({ name: "example_get_user", arguments: { user_id: page.users[0].id } });
  assert.ok(!user.isError, `get_user failed: ${JSON.stringify(user.content)}`);
}

// Invalid arguments must come back as a tool error the model can read
const invalid = await client.callTool({ name: "example_search_users", arguments: { query: "j" } });
assert.equal(invalid.isError, true, "a one-character query should be rejected");

await client.close();
console.error("Smoke test passed");
  • Call read-only tools with realistic arguments; check that one invalid input is rejected
  • StdioClientTransport gives the child process only a safe default environment (PATH, HOME, and similar), so pass API keys and other settings in env
  • For an HTTP server, start it (TRANSPORT=http npm start) and connect with new StreamableHTTPClientTransport(new URL("http://127.0.0.1:3000/mcp")) from @modelcontextprotocol/client instead
  • For manual exploration, npx @modelcontextprotocol/inspector node dist/index.js opens an interactive UI
  • More test patterns, including in-process tests without a subprocess: https://ts.sdk.modelcontextprotocol.io/v2/testing.md

More Features

Each linked example is a runnable server and client pair from the SDK repository:

| To... | See | |---|---| | Report progress, send log messages, and handle cancellation in long-running tools | streaming | | Ask the user for input mid-call (elicitation) | elicitation | | Notify subscribed clients when resources change | subscriptions | | Add OAuth login (authorization code flow) | oauth | | Accept machine-to-machine OAuth (client credentials) | oauth-client-credentials | | Require different scopes for different tools | scoped-tools | | Serve on Hono or another web-standard runtime | hono, bearer-auth-web | | Run sessionful 2025-era HTTP deployments | standalone-get, sse-polling | | See every server feature in one reference server | todos-server |


Migrating a v1 Server

To move an existing @modelcontextprotocol/sdk server to v2, run the official codemod at the package root, then fix what it marks:

npx @modelcontextprotocol/codemod@latest v1-to-v2 .
grep -rn '@mcp-codemod-error' .   # Spots the codemod could not rewrite safely
npx tsc --noEmit

The codemod rewrites imports, package.json, registration calls, and handler context access. Check that zod ends up at ^4.2.0 or later, then run your formatter and tests. The full guide is at https://ts.sdk.modelcontextprotocol.io/v2/migration/upgrade-to-v2.md.


Quality Checklist

Tool Design

  • [ ] Tools enable complete workflows, not just API endpoint wrappers
  • [ ] Tool names are snake_case with a service prefix
  • [ ] Every tool has a title, a description that says when to use it, and correct annotations
  • [ ] Inputs are Zod object schemas with constraints and .describe() text; z.strictObject where unknown arguments should be rejected
  • [ ] List and search tools paginate with limit / offset and return next_offset
  • [ ] Responses stay under CHARACTER_LIMIT by returning fewer items
  • [ ] Results with structuredContent also include that data serialized as JSON text; outputSchema only on always-JSON tools
  • [ ] Error messages say what went wrong and how to recover

Implementation

  • [ ] createServer() returns a new McpServer on every call, with everything registered inside it; shared clients live at module scope
  • [ ] Upstream requests pass ctx.mcpReq.signal and have a timeout
  • [ ] Strict TypeScript; no any; upstream data validated where it feeds structuredContent
  • [ ] Nothing writes to stdout in a stdio server
  • [ ] HTTP servers keep Host/Origin validation, and add bearer auth when exposed beyond localhost

Project

  • [ ] package.json depends on @modelcontextprotocol/server (not @modelcontextprotocol/sdk) and zod ^4.2.0 or later
  • [ ] No imports from @modelcontextprotocol/sdk/... or zod/v3
  • [ ] bin points at dist/index.js, and src/index.ts starts with #!/usr/bin/env node

Verification

  • [ ] npm run build completes without errors
  • [ ] The self-check script passes against the built server