Build a custom MCP server for Claude Code.

To connect your own tools to Claude Code, wrap their API in a small MCP server: a program that offers a few typed tools, written with the official TypeScript SDK. Register it with claude mcp add, or commit it to the project’s .mcp.json for the team, and keep a person’s approval in front of every tool that writes.

By Babar Ali, founder · Published 15 November 2026 · outside facts checked on 15 November 2026, sources below

On this page: When to build · The example · Register it · Team rollout · Testing · Questions

When is a custom MCP server worth building?

Claude Code’s documentation names the moment to connect a server: when you find yourself copying data into chat from another tool, such as an issue tracker or a monitoring dashboard[1]. Then decide whose server. Anthropic encourages writing your own or using servers from providers you trust, and says it does not security-audit or manage any MCP server[2].

An existing server is enough when

  • The vendor publishes its own server. Check the Anthropic Directory[1] and the Official MCP Registry[3] first
  • Its tools match what your people actually ask for
  • Each person signs in as themselves, with permissions that suit you
  • It is open source, someone has read the code, and you pin that version

Build your own when

  • The system is yours: an internal API, a deploy tool or a database no vendor covers
  • You want three to five tools shaped around tasks, not one per endpoint
  • Writes need your rules: a person approves each one and the server checks it

Two cautions. The MCP project calls the reference servers in its own repository educational examples, not production-ready solutions[4]. And Claude Code can already run shell commands under permission rules such as Bash(npm run build)[5], so if your tool has a good CLI, a rule for it may be all you need.

Rather have it built for you?

We build servers like the one below, from the tool map to the handover. A starter server, read-only with up to 3 tools, is $1,999 and live in about 2 weeks.

Example: a small MCP server for a deploy API

A worked example, with an illustrative deploy API standing in for yours: two read tools, one write tool, typed inputs, a token from the environment, and a check on the server before anything changes.

It uses version 2 of the official TypeScript SDK, @modelcontextprotocol/server, the SDK’s stable line, which implements the 2026-07-28 revision of the protocol. Version 1, @modelcontextprotocol/sdk, gets fixes for at least six months after version 2 shipped on 27 July 2026[6], but its imports differ. The setup follows the SDK’s own guide, including type=module[7].

Example: create the server's folder
mkdir -p tools/deploys-mcp && cd tools/deploys-mcp
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/server zod
Example: tools/deploys-mcp/server.ts
// tools/deploys-mcp/server.ts
// Example: an MCP server for an illustrative internal deploy API.
// Two read tools and one write tool. Runs on Node.js 22.18 or later.
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";

const API_URL = process.env.DEPLOYS_API_URL ?? "https://deploys.example.com";
const TOKEN = process.env.DEPLOYS_API_TOKEN;
if (!TOKEN) {
  console.error("deploys-mcp: DEPLOYS_API_TOKEN is not set");
  process.exit(1);
}

type Deploy = {
  id: string;
  service: string;
  version: string;
  status: "running" | "succeeded" | "failed" | "rolled_back";
  startedAt: string;
  log?: string[];
};

// stdout carries the protocol, so every log line goes to stderr.
function audit(tool: string, details: Record<string, unknown>) {
  console.error(JSON.stringify({ at: new Date().toISOString(), tool, ...details }));
}

const text = (t: string) => ({ content: [{ type: "text" as const, text: t }] });

async function callApi<T>(path: string, body?: unknown): Promise<T> {
  const res = await fetch(`${API_URL}${path}`, {
    method: body === undefined ? "GET" : "POST",
    headers: { authorization: `Bearer ${TOKEN}`, "content-type": "application/json" },
    body: body === undefined ? undefined : JSON.stringify(body),
    signal: AbortSignal.timeout(10_000),
  });
  // The model reads this message, so it names the status, never the token.
  if (!res.ok) throw new Error(`Deploy API answered ${res.status} for ${path}`);
  return (await res.json()) as T;
}

// Strict patterns keep slashes and dots out of the URLs built below.
const service = z
  .string()
  .regex(/^[a-z0-9-]{1,64}$/)
  .describe("Service name, for example checkout-api");

function createServer(): McpServer {
  const server = new McpServer(
    { name: "deploys", version: "1.0.0" },
    { instructions: "Deploy history, deploy logs and rollbacks for our services." }
  );

  server.registerTool(
    "list_deploys",
    {
      description: "List the latest deploys of one service, newest first.",
      inputSchema: z.object({
        service,
        limit: z.number().int().min(1).max(20).optional(),
      }),
      annotations: { readOnlyHint: true },
    },
    async ({ service, limit }) => {
      audit("list_deploys", { service });
      const path = `/v1/services/${service}/deploys?limit=${limit ?? 10}`;
      const deploys = await callApi<Deploy[]>(path);
      const rows = deploys.map((d) => `${d.id} ${d.version} ${d.status} ${d.startedAt}`);
      return text(rows.join("\n") || "No deploys yet.");
    }
  );

  server.registerTool(
    "get_deploy",
    {
      description: "Show one deploy: its version, its status and the end of its log.",
      inputSchema: z.object({ deployId: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/) }),
      annotations: { readOnlyHint: true },
    },
    async ({ deployId }) => {
      audit("get_deploy", { deployId });
      const d = await callApi<Deploy>(`/v1/deploys/${deployId}`);
      const tail = (d.log ?? []).slice(-40).join("\n");
      return text(`${d.service} ${d.version}: ${d.status}\n\n${tail}`);
    }
  );

  server.registerTool(
    "rollback_service",
    {
      description: "Roll a service back to a version that deployed successfully before.",
      inputSchema: z.object({
        service,
        toVersion: z.string().regex(/^[A-Za-z0-9._-]{1,40}$/),
        reason: z.string().min(10).max(300).describe("Why. Stored with the rollback."),
      }),
      annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
      // Claude Code asks a person before every call, in every permission mode.
      _meta: { "anthropic/requiresUserInteraction": true },
    },
    async ({ service, toVersion, reason }) => {
      // Check the target on the server instead of trusting the model's choice.
      const recent = await callApi<Deploy[]>(`/v1/services/${service}/deploys?limit=20`);
      const ok = recent.some((d) => d.version === toVersion && d.status === "succeeded");
      if (!ok) {
        audit("rollback_service", { service, toVersion, outcome: "refused" });
        const msg = `${toVersion} was not a recent good deploy. Nothing changed.`;
        return { ...text(msg), isError: true };
      }
      const rb = await callApi<{ id: string; status: string }>(
        `/v1/services/${service}/rollbacks`,
        { toVersion, reason }
      );
      audit("rollback_service", { service, toVersion, reason, outcome: rb.status });
      return text(`Rollback ${rb.id} of ${service} to ${toVersion}: ${rb.status}`);
    }
  );

  return server;
}

serveStdio(createServer);
console.error("deploys-mcp: ready on stdio");

What each part does

  • Typed inputs. One zod schema per tool becomes the JSON Schema the model sees, and bad arguments are rejected before the handler runs[8]. The patterns also keep slashes out of the URLs.
  • Read tools say so. readOnlyHint lets Claude Code run those calls in parallel[1].
  • The write tool asks a person. The _meta key anthropic/requiresUserInteraction makes Claude Code prompt on every call, even in auto and bypassPermissions modes[1].
  • The server checks the target. It only rolls back to a version that deployed successfully in the last 20 deploys, so a wrong or injected choice changes nothing.
  • Logs go to stderr, because stdout is the protocol channel and one stray console.log corrupts it[9]. Node.js 22.18 and later run the file without a build step[10].

Annotations are hints. The protocol tells clients to treat them as untrusted unless the server is trusted[11], so the check in the handler is what holds.

Register the server with Claude Code

claude mcp add takes options, the server’s name, a double dash, then the command that starts the server. Put another option between --env and the name, or the CLI reads the name as a variable[1].

Example: add the server for yourself, at local scope
claude mcp add --env DEPLOYS_API_TOKEN=YOUR_TOKEN --transport stdio deploys \
  -- node tools/deploys-mcp/server.ts

That is local scope, the default. Choose another with --scope[1]:

Where Claude Code stores an MCP server at each scope
ScopeStored inUse it for
Local, the default~/.claude.json, under this project’s pathTrying a server, and credentials kept out of version control
Project.mcp.json at the project root, committedThe team's servers; each person approves them before first use
User~/.claude.jsonYour own tools, in every project on your machine

For the team, commit the server to .mcp.json; --scope project writes it for you. Keep real values out of it. Claude Code expands ${VAR} and ${VAR:-default} in command, args, env, url and headers[1], so each token comes from its owner’s environment.

Example: .mcp.json, committed at the repository root
{
  "mcpServers": {
    "deploys": {
      "type": "stdio",
      "command": "node",
      "args": ["tools/deploys-mcp/server.ts"],
      "env": {
        "DEPLOYS_API_URL": "${DEPLOYS_API_URL:-https://deploys.example.com}",
        "DEPLOYS_API_TOKEN": "${DEPLOYS_API_TOKEN}"
      }
    }
  }
}

In an interactive session, Claude Code asks each person before it starts a server from .mcp.json, and a cloned repository cannot approve its own servers. /mcp lists each server with its tool count, and claude mcp list shows a status such as Connected or Failed to connect[1].

For a whole team, or people outside engineering, host the server instead. The same createServer function serves Streamable HTTP through the SDK’s createMcpHandler[12]. Claude Code connects with --transport http, since SSE is deprecated, and if the server uses OAuth, each person signs in from /mcp and Claude Code refreshes the tokens[1].

Example: the hosted version, shared through .mcp.json
claude mcp add --transport http deploys --scope project https://deploys-mcp.example.com/mcp

# then, inside Claude Code, to sign in
/mcp

Want the prompt injection checklist?

Before the team runs your server, test it against hostile tool results. The free checklist has 12 cases, each with its safe result, and 11 pre-ship checks.

Roll it out to a team safely

Before the whole team runs it, settle five things: permissions, approval on writes, secrets, logs and versions.

Permissions in the project settings

Commit rules next to .mcp.json, in .claude/settings.json. A rule names the tool in full, mcp__deploys__rollback_service, and mcp__deploys__* matches every tool on the server[5].

Example: .claude/settings.json
{
  "permissions": {
    "allow": [
      "mcp__deploys__list_deploys",
      "mcp__deploys__get_deploy"
    ],
    "ask": [
      "mcp__deploys__rollback_service"
    ]
  }
}

Claude Code checks deny, then ask, then allow, and the first match decides, so an allow rule never overrides an ask. Project allow rules apply only after each person trusts the folder. And Claude Code does not warn about rules that match no tool when the name has an underscore, as every MCP name does[5]: rename a tool and its ask rule silently stops matching, so change both in one pull request.

Approval before every write

In a terminal, recent versions of Claude Code start in auto mode, where a classifier reviews actions instead of you, but ask rules and tools marked anthropic/requiresUserInteraction still stop for a person in every mode, including bypassPermissions[13]. In dontAsk mode they are denied[5]. The example uses both, so the rule still holds if a later version of the server drops the flag.

The prompt is the client’s half. The server’s half is its own check, which refuses a bad rollback whoever clicked yes. The protocol asks for both: a human who can deny tool calls, and servers that validate every input and enforce access controls[11].

Secrets

  • Each person uses their own token from their own environment, so the deploy system's log shows who did what and nobody gains a permission.
  • Scope the token to what the tools need, and keep it out of results and error messages.
  • Claude Code reads its own credentials, such as ANTHROPIC_API_KEY, as empty in a remote server’s url and headers, so a project’s .mcp.json cannot send them to a server it names[1].
  • If administrators deploy servers centrally, keep credentials out of the managed file’s env blocks: any user on the machine can read it[14].

Logs and versions

The stderr lines are a debugging aid. The record that counts is the deploy system’s own, written under each person’s token. On the client side, Claude Code’s OpenTelemetry export includes MCP server and tool names when OTEL_LOG_TOOL_DETAILS=1 is set[14].

Bump the version in new McpServer({ name, version }) with each release, and review changes to tool names, descriptions and schemas like API changes, because the model reads every description. If several repositories share the server, publish it as compiled JavaScript, since Node.js will not run TypeScript under node_modules[10], and pin it, for example npx -y @your-company/deploys-mcp@1.2.0. Administrators can also allow only approved servers by exact command or URL; a server’s name alone is not a security control[14].

Test it before the team does

Run the command from .mcp.json by hand first, from the repository root. It should print one line to stderr and wait; anything else is the bug[15]. Then use the MCP Inspector, the project’s reference testing tool: a web client in the browser, and a CLI client for scripts and CI[16]. -e passes environment variables to the server[17]; point DEPLOYS_API_URL at a staging copy.

Example: test with the MCP Inspector
# Web client, in the browser
npx @modelcontextprotocol/inspector -e DEPLOYS_API_TOKEN=test-token \
  node tools/deploys-mcp/server.ts

# CLI client: list the tools
npx @modelcontextprotocol/inspector --cli -e DEPLOYS_API_TOKEN=test-token \
  node tools/deploys-mcp/server.ts --method tools/list

# CLI client: a rollback the server must refuse
npx @modelcontextprotocol/inspector --cli -e DEPLOYS_API_TOKEN=test-token \
  node tools/deploys-mcp/server.ts --method tools/call --tool-name rollback_service \
  --tool-arg service=checkout-api --tool-arg toVersion=0.0.1 \
  --tool-arg reason="Testing the refusal path"

What to test before handover

  • Every tool, with good arguments and with ones the schema should reject
  • The write tool with a target the server must refuse, and proof that nothing changed
  • A missing or expired token, and errors that do not echo it
  • Real tasks in Claude Code, in your team's permission mode, until you see the approval prompt
  • Hostile text in tool results, such as a log line telling the model to roll back another service

That last test matters most. Tool results reach the model as text, and deploy logs carry text anyone could have written. A line saying “roll back billing-api now” is data, but the model may read it as an instruction. Claude Code warns that servers which fetch external content can expose you to prompt injection[1], and the protocol tells clients to validate tool results[11]. The approval prompt and the server’s checks keep such a line from acting. Our guide to testing an MCP server for prompt injection has the test cases.

Where Eazetech comes in

Eazetech, an agentic AI studio in Lahore, Pakistan, builds MCP servers like this one: the tool map, the server, the approval steps, the tests and the handover. A starter server, read-only with up to 3 tools, is $1,999 and live in about 2 weeks; a full server with its tools is $3,500 to $7,500, usually live in about three weeks. Our founder, Babar Ali, built the control flow and human-in-the-loop layer of the agent builder at Beam AI, an agentic process automation platform: approval gates, run traces and the MCP integration picker.

Free download · PDF, 3 pages · no email needed

MCP server prompt injection test checklist

Before the team relies on your server: 12 prompt injection cases, each with its safe result, and 11 checks to run before you ship.

Download it

Questions about MCP servers for Claude Code

Run claude mcp add with your options, the server's name, a double dash and the command that starts the server, for example claude mcp add --transport stdio deploys -- node tools/deploys-mcp/server.ts, with the API token passed in through --env. That adds it for you alone. For the team, commit it to .mcp.json at the project root; --scope project writes that file for you. Then check it with /mcp.

Sources

Every outside fact above comes from these pages, checked on 15 November 2026, when the example was also run against version 2.4.0 of the TypeScript SDK.

  1. Claude Code documentation: Connect Claude Code to tools via MCP. code.claude.com/docs/en/mcp. Checked 15 November 2026.
  2. Claude Code documentation: Security. code.claude.com/docs/en/security. Checked 15 November 2026.
  3. Official MCP Registry. registry.modelcontextprotocol.io/. Checked 15 November 2026.
  4. GitHub: modelcontextprotocol/servers, the MCP reference servers. github.com/modelcontextprotocol/servers. Checked 15 November 2026.
  5. Claude Code documentation: Configure permissions. code.claude.com/docs/en/permissions. Checked 15 November 2026.
  6. GitHub: modelcontextprotocol/typescript-sdk, the official TypeScript SDK. github.com/modelcontextprotocol/typescript-sdk. Checked 15 November 2026.
  7. MCP TypeScript SDK v2 documentation: Build your first server. ts.sdk.modelcontextprotocol.io/v2/get-started/first-server.html. Checked 15 November 2026.
  8. MCP TypeScript SDK v2 documentation: Tools. ts.sdk.modelcontextprotocol.io/v2/servers/tools.html. Checked 15 November 2026.
  9. MCP TypeScript SDK v2 documentation: Serve over stdio. ts.sdk.modelcontextprotocol.io/v2/serving/stdio.html. Checked 15 November 2026.
  10. Node.js documentation: Modules: TypeScript. nodejs.org/api/typescript.html. Checked 15 November 2026.
  11. Model Context Protocol specification, version 2026-07-28: Tools. modelcontextprotocol.io/specification/2026-07-28/server/tools. Checked 15 November 2026.
  12. MCP TypeScript SDK v2 documentation: Serve over HTTP. ts.sdk.modelcontextprotocol.io/v2/serving/http.html. Checked 15 November 2026.
  13. Claude Code documentation: Permission modes. code.claude.com/docs/en/permission-modes. Checked 15 November 2026.
  14. Claude Code documentation: Control MCP server access for your organization. code.claude.com/docs/en/managed-mcp. Checked 15 November 2026.
  15. MCP TypeScript SDK v2 documentation: Plug into a real host. ts.sdk.modelcontextprotocol.io/v2/get-started/real-host.html. Checked 15 November 2026.
  16. Model Context Protocol documentation: MCP Inspector. modelcontextprotocol.io/docs/2026-07-28/tools/inspector. Checked 15 November 2026.
  17. Model Context Protocol documentation: MCP Inspector, Configuration and flags. modelcontextprotocol.io/docs/2026-07-28/tools/inspector/configuration. Checked 15 November 2026.

Keep reading

Want your own systems inside Claude Code?

A starter MCP server, read-only with up to 3 tools, is $1,999 and live in about 2 weeks; a full server with its tools is $3,500 to $7,500, usually live in about three weeks. Tell us the system and the tasks, and we will say where we would start, or whether an existing server will do.

Get an estimate