build-mcp
Build an MCP server end to end, tailored to how it will be used. Use when asked to build an MCP, create an MCP server, wrap an API as a tool, make a tool for Claude, expose a service to an agent, build a Claude connector, or turn a service into MCP tools. Asks up front who the se
Install
npx skills add https://github.com/techwolf-ai/ai-first-toolkit/tree/main/plugins/tool-build-kit/skills/build-mcp
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install techwolf-ai-ai-first-toolkit@llmmart
git clone https://github.com/techwolf-ai/ai-first-toolkit.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole techwolf-ai/ai-first-toolkit collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
Build MCP
Build a Model Context Protocol (MCP) server the right way, end to end. The defining move of this skill: establish the user's context with AskUserQuestion before building anything, then tailor every phase to that context. A personal local server and a public hosted server share almost no steps past "build", so branch early and commit to the branch.
How this relates to mcp-builder
The Anthropic example-skills:mcp-builder skill is the gold-standard reference for the implementation itself: FastMCP and TypeScript SDK patterns, tool design, input/output schemas, annotations, error handling, and evaluation. Do not duplicate it. This skill is the scope-and-distribution wrapper around it: it decides what to build, for whom, where it runs, and how it ships. When you reach the build phase, invoke example-skills:mcp-builder for the deep implementation guidance and keep this skill's references thin.
The five phases
- Analyze: understand the service to wrap and pick the right tool boundaries.
- Build: scaffold and implement the server (delegates to mcp-builder).
- Deploy: get it running and registered for the target runtime.
- Scale: harden and operate it (only substantive for hosted servers).
- Distribute: make it reachable by the intended audience.
Run them in order. The AskUserQuestion answers from Phase 0 gate phases 3, 4, and 5.
Phase 0: Establish context (AskUserQuestion, do this first)
Before analyzing or writing anything, branch on the user's context. Ask the audience question first; it is the headline decision and it cascades into everything downstream. Then ask runtime only if it is still ambiguous, and ask language after Analyze (so you can recommend based on the wrapped service).
Question 1 (always, ask first): Audience / scope:
Use AskUserQuestion:
- header: "Audience"
- question: "Who is this MCP server for? This decides how we deploy and distribute it."
- options:
- "Just me": personal local tool on my machine.
- "My team / org": shared internally, installed by colleagues.
- "Public / external": published openly for anyone to install.
Question 2 (conditional): Where it runs:
Skip for "Just me" (assume local stdio). Ask for org/public when unclear:
- header: "Runtime"
- question: "Where should the server run?"
- options:
- "Local stdio": runs as a subprocess on each user's machine. Simplest. Each user supplies their own secrets.
- "Hosted HTTP": one Streamable HTTP server many users connect to. Needs auth, deploy, and scaling.
Question 3 (after Analyze): Language:
- header: "Language"
- question: "What should the server be written in?"
- options:
- "Python (FastMCP)": fastest path, great for wrapping Python-friendly APIs.
- "Node / TypeScript (MCP SDK)": the mcp-builder ecosystem default (strongest SDK, models write TS well, best MCPB compatibility). Pick it when torn, or when the service has a strong TS SDK or you ship via npm.
- "Recommend for me": pick based on the service analyzed in Phase 1; lean TypeScript unless the wrapped service is clearly Python-friendly.
Ask one question at a time. Confirm the resolved context back to the user in one line before proceeding (e.g. "Building a personal, local, Python stdio server that wraps the Linear API"). That resolved tuple drives the branch table below.
Branch table (the spine of this skill)
| Phase | Just me (local stdio) | My org (local stdio) | My org (hosted HTTP) | Public (package) | Public (hosted HTTP) |
|---|---|---|---|---|---|
| Deploy | claude mcp add --scope user or .mcp.json |
Bundle in a Claude Code plugin; ${CLAUDE_PLUGIN_ROOT} paths |
Deploy Streamable HTTP endpoint + OAuth/bearer | Publish to PyPI/npm; users run via uvx/npx |
Deploy HTTP endpoint; document the URL |
| Scale | N/A (keep it maintainable) | N/A per-user; version the plugin | Real: statelessness, sessions, auth, rate limits | Versioning + backward-compat tool changes | Full: statelessness, auth, rate limits, observability |
| Distribute | Not shared. Stop after registration. | Org marketplace (.claude-plugin/marketplace.json + /plugin install) |
Org marketplace entry pointing at the hosted URL | PyPI/npm + MCP registry via mcp-publisher |
MCP registry remotes entry + public docs |
If a phase says N/A for the chosen branch, say so explicitly and move on. Do not pad it.
Reference files for each branch:
- references/transports.md: stdio vs Streamable HTTP, when each applies, the
http/streamable-httpnaming gotcha. - references/deploy-local.md:
claude mcp add, scopes,.mcp.json, Claude Desktop config, uvx/npx run configs. - references/distribute-marketplace.md: bundling an MCP server in a Claude Code plugin, org marketplace, the public MCP registry.
- references/scaling.md: hosted-server statelessness, sessions, auth, versioning, security.
- references/python-fastmcp.md and references/node-sdk.md: thin quickstarts that hand off to mcp-builder.
Load only the references the current branch and phase need. Progressive disclosure.
Phase 1: Analyze
Understand what you are wrapping before you write tools. Output a short tool plan, then confirm it.
- Identify the service/API. Read its docs or SDK. Note auth model (API key, OAuth, none), base URL, rate limits, pagination style.
- Pick tool boundaries. This is a real tradeoff, framed the way mcp-builder frames it: comprehensive API coverage gives agents flexibility to compose operations, while specialized workflow tools are more convenient for specific tasks. Performance is client-dependent (some clients do better with code execution over basic tools, others with higher-level workflows). When uncertain, default to comprehensive API coverage rather than a few workflow tools. Either way each tool does one focused thing with a clear, action-oriented name. (mcp-builder has the full tool-design rubric; apply it here.)
- Decide read vs write. Mark which tools are read-only and which mutate state; this becomes the
readOnlyHint/destructiveHintannotations later. - Scope the secrets. What credentials does each tool need? For "Just me" they live in local env. For hosted, they live server-side and must never be passed through from the client (see scaling.md).
- Now ask the language question (Phase 0 Q3) if it was deferred, recommending based on what you found.
Deliverable: a numbered list of proposed tools, each with name, one-line purpose, inputs, read/write, and the service call it makes. Confirm with the user before building.
Phase 2: Build
Hand off to the implementation reference for the chosen language, which in turn defers to mcp-builder for depth.
- Python: read references/python-fastmcp.md, then invoke
example-skills:mcp-builderfor the full FastMCP guide. - Node/TS: read references/node-sdk.md, then invoke
example-skills:mcp-builderfor the full TypeScript SDK guide.
Build to the tool plan from Phase 1. Apply mcp-builder's rules: clear tool names, Pydantic/Zod input schemas with descriptions and constraints, structured + human-readable output, pagination with limits, actionable error messages, and tool annotations. Compile and test with the MCP Inspector (npx @modelcontextprotocol/inspector) before moving on. Then write and run mcp-builder's evaluation set: about 10 realistic, read-only, verifiable questions in its XML format, scored with its scripts/evaluation.py harness (e.g. python scripts/evaluation.py -t stdio -c python -a server.py -o report.md evaluation.xml). Do not hand-wave this; a server that the eval can't drive is not done.
Start the server on stdio regardless of final runtime; it is the simplest thing to test locally. Switching to Streamable HTTP is a transport change at the end, not a rewrite (see transports.md).
Phase 3: Deploy
Branch on the resolved runtime. Read references/deploy-local.md for stdio, references/transports.md for HTTP.
- Local stdio (just me, or org-local): register it.
claude mcp add --scope user <name> -- <command> <args>for a personal server across all your projects, or a project-scoped.mcp.json. Verify withclaude mcp listand/mcp. For org-local distribution, you do not register by hand on each machine; you bundle into a plugin (Phase 5). - Hosted HTTP: expose a single Streamable HTTP endpoint (POST+GET on one path). Validate the
Originheader, bind to localhost when local, require auth. Connect withclaude mcp add --transport http <name> <url>(add--header "Authorization: Bearer ..."for static tokens, or rely on the OAuth 401/WWW-Authenticatediscovery flow). Containerize for repeatable deploys.
Phase 4: Scale
Only substantive for hosted HTTP servers. For local/personal servers, state plainly that scaling is N/A and that the priority is maintainability and versioning, then skip to Distribute.
For hosted servers, read references/scaling.md and cover: stateless vs session-bearing design (Mcp-Session-Id), horizontal scaling, auth as an OAuth 2.1 resource server (validate token audience, never pass tokens through), least-privilege scopes, rate limiting, timeouts, observability, and protocol-version negotiation. Carry the caveat that there is no Anthropic-published "operate an MCP server" guide; this rests on the MCP spec plus normal infra practice.
Phase 5: Distribute
The payoff phase. Branch hard on the audience answer. Read references/distribute-marketplace.md.
- Just me: nothing to distribute. The server is registered (Phase 3). Stop here; confirm it works in a session.
- My org / team: package as a Claude Code plugin and list it in your org's
.claude-plugin/marketplace.json. The plugin ships the server via anmcpServerskey inplugin.jsonor a bundled.mcp.json(use${CLAUDE_PLUGIN_ROOT}for bundled paths). Colleagues run/plugin marketplace add <org>/<repo>then/plugin install <name>@<marketplace>. For auto-provisioning, add the marketplace to the project's.claude/settings.jsonunderextraKnownMarketplaces. The TechWolfai-first-toolkitrepo is a working example of this layout. - Public / external: publish the package first (PyPI for Python, npm for Node), then register metadata with the MCP registry using the
mcp-publisherCLI (init->login github->publish). For a hosted public server, register aremotesentry pointing at your URL instead of a package. Note the registry is in preview and its schema can change.
You can do more than one (e.g. an org plugin and a public package). Distribution paths are additive.
Done criteria
- The server compiles, the Inspector lists the tools, and the evaluation set passes.
- It is registered or published for the resolved audience, and you verified it loads in a real Claude session.
- The user can name how a colleague (or the public) would install it, matching their audience answer.
Files (ai-first-toolkit)
-
references
-
deploy-local.md 4 KB
# Deploy: local registration How to register a finished server so Claude can use it. For the "just me" and org-local-stdio branches this is the whole deploy phase. For hosted servers, see the HTTP section at the end and `references/scaling.md`. > The commands below are current as of writing but the CLI moves fast. Verify against the live docs before relying on exact flags: `https://code.claude.com/docs/en/mcp` (Claude Code MCP) and `https://modelcontextprotocol.io/docs/develop/connect-local-servers`. Fetch any modelcontextprotocol.io page as markdown by appending `.md` to the URL. ## claude mcp add (stdio) Options come before the name. `--` separates Claude's flags from the server command; everything after `--` is passed to the server untouched. ```bash claude mcp add [options] <name> -- <command> [args...] ``` Example, a uvx-published Python server with an env var: ```bash claude mcp add --env SERVICE_API_KEY=sk-xxx --scope user service -- uvx service-mcp ``` Gotcha: do not put the server name immediately after `--env`, or the CLI reads the name as another `KEY=value` pair. Keep at least one other option between `--env` and the name. ### Scopes | Scope | Loads in | Shared | Stored in | |-------|----------|--------|-----------| | `local` (default) | current project only | no | `~/.claude.json` keyed by project path | | `project` | current project | yes, via version control | `.mcp.json` in project root | | `user` | all your projects | no | `~/.claude.json` | For a personal server you use everywhere, pick `--scope user`. For a server tied to one repo, use `project` so it lands in a committed `.mcp.json`. ## .mcp.json (project scope) ```json { "mcpServers": { "service": { "command": "uvx", "args": ["service-mcp"], "env": { "SERVICE_API_KEY": "${SERVICE_API_KEY}" } } } } ``` - Env-var expansion works in `command`, `args`, `env`, `url`, `headers`: `${VAR}` and `${VAR:-default}`. A required-but-unset var with no default fails parsing. - Project-scoped servers require user approval before first use (`claude mcp reset-project-choices` resets approvals). - Optional per-server fields: `timeout` (ms, hard per-tool-call wall-clock limit), `alwaysLoad: true` (exempt from Tool Search deferral). ## Run-on-demand configs (no install step) Node via npx: ```json { "mcpServers": { "weather": { "command": "npx", "args": ["-y", "@you/mcp-weather"] } } } ``` Python via uvx: ```json { "mcpServers": { "db": { "command": "uvx", "args": ["db-query-mcp"], "env": { "DB_URL": "..." } } } } ``` ## Claude Desktop Config file: macOS `~/Library/Application Support/Claude/claude_desktop_config.json`, Windows `%APPDATA%\Claude\claude_desktop_config.json`. Same `mcpServers` shape: ```json { "mcpServers": { "service": { "command": "uvx", "args": ["service-mcp"], "env": { "SERVICE_API_KEY": "..." } } } } ``` ## Hosted HTTP registration ```bash claude mcp add --transport http service https://service.example.com/mcp # static bearer token: claude mcp add --transport http service https://service.example.com/mcp \ --header "Authorization: Bearer your-token" ``` If the server returns 401/403 with a `WWW-Authenticate` header, Claude runs the OAuth discovery flow; the user completes it via `/mcp`. See `references/scaling.md` for the auth model. ## CLAUDE_PROJECT_DIR Claude Code sets `CLAUDE_PROJECT_DIR` in every spawned stdio server's environment, pointing at the project root the Claude session was launched from. Read it inside your server (`os.environ["CLAUDE_PROJECT_DIR"]` in Python, `process.env.CLAUDE_PROJECT_DIR` in Node) to resolve project-relative paths without depending on the working directory. In `.mcp.json` `command`/`args`, reference it with a default (`${CLAUDE_PROJECT_DIR:-.}`) since it is set in the server's environment at runtime, not during config parsing. ## Verify ```bash claude mcp list # shows configured servers and connection status claude mcp get <name> ``` Then open a session and run `/mcp` to confirm the tools load. -
distribute-marketplace.md 5.7 KB
# Distribute: org marketplace and public registry The distribute phase, branched by audience. Pick the path(s) that match the Phase 0 answer. They are additive: you can ship an org plugin and a public package. > Distribution mechanics change quickly (the plugin system and the registry are both young). Verify before relying on exact syntax: plugins and marketplaces at `https://code.claude.com/docs/en/plugins` and `https://code.claude.com/docs/en/plugin-marketplaces`; the registry at `https://modelcontextprotocol.io/registry`. Append `.md` to any modelcontextprotocol.io URL to fetch it as markdown. ## Org / team: bundle as a Claude Code plugin The cleanest way to give colleagues an MCP server is a Claude Code plugin that ships the server. Installing the plugin auto-registers the server, so nobody runs `claude mcp add` by hand. ### Declare the server in the plugin Two equivalent, documented ways: 1. A standalone `.mcp.json` in the plugin root (auto-discovered): ```json { "mcpServers": { "service": { "command": "${CLAUDE_PLUGIN_ROOT}/servers/service-server", "args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"], "env": { "SERVICE_API_KEY": "${SERVICE_API_KEY}" } } } } ``` 2. An `mcpServers` key in `.claude-plugin/plugin.json` (a path string, an array of paths, or an inline object): ```json { "name": "service-tools", "version": "0.1.0", "mcpServers": "./.mcp.json" } ``` Use `${CLAUDE_PLUGIN_ROOT}` for any bundled paths, because marketplace plugins are copied into `~/.claude/plugins/cache`. Plugin MCP servers start automatically when the plugin is enabled and go through the same per-server approval as a project `.mcp.json`. Run `/reload-plugins` after enabling, or after changing a bundled `.mcp.json`. Note: a plugin's *agents* cannot declare their own `mcpServers` (security restriction); declare at the plugin level. ### List it in a marketplace `.claude-plugin/marketplace.json` at the marketplace repo root: ```json { "name": "company-tools", "owner": { "name": "DevTools Team", "email": "devtools@example.com" }, "plugins": [ { "name": "service-tools", "source": "./plugins/service-tools", "description": "MCP tools for the internal service", "version": "0.1.0" } ] } ``` Required: top-level `name` (kebab-case), `owner.name`, and a `plugins[]` array where each entry has at least `name` and `source`. `source` is a relative path string or an object like `{ "source": "github", "repo": "org/repo" }`. The TechWolf `ai-first-toolkit` repo is a live example of this layout. ### Install flow for colleagues ```bash /plugin marketplace add your-org/claude-plugins # owner/repo shorthand for GitHub /plugin install service-tools@company-tools /reload-plugins ``` CLI equivalents exist (`claude plugin marketplace add ...`, `claude plugin install ...@... --scope project`). ### Auto-provision for the whole team Add the marketplace to the project's `.claude/settings.json` so anyone who trusts the folder is prompted to install: ```json { "extraKnownMarketplaces": { "company-tools": { "source": { "source": "github", "repo": "your-org/claude-plugins" } } } } ``` ### Versioning lever Set `version` (semver) in `plugin.json` and users only get updates when you bump it. Omit it everywhere and Claude Code falls back to the git commit SHA, treating every commit as a new version. `plugin.json` wins over the marketplace entry. ## Public: package managers + the MCP registry The official MCP registry holds **metadata only, not artifacts**. Publish the package first, then register metadata. > Caveat: the registry is in preview. Its schema and commands can change, and data resets may occur before general availability. Treat this section as the least stable part of the workflow and re-check `modelcontextprotocol.io/registry` before publishing. ### Steps with the mcp-publisher CLI ```bash # 0. add mcpName to package.json (npm only — required for ownership verification) # the registry checks this field matches server.json `name` before accepting publish # "mcpName": "io.github.<username>/<server-name>" # 1. publish the package to its registry npm publish --access public # or: build + upload to PyPI # 2. install the publisher CLI brew install mcp-publisher # or download the binary from registry releases # 3. scaffold server.json mcp-publisher init # 4. authenticate (GitHub namespace requires GitHub auth) mcp-publisher login github # 5. publish metadata mcp-publisher publish ``` GitHub auth means the server name must start with `io.github.<your-username>/`. `server.json` for an npm stdio package: ```json { "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", "name": "io.github.you/service", "description": "An MCP server for the service.", "repository": { "url": "https://github.com/you/service-mcp", "source": "github" }, "version": "1.0.0", "packages": [ { "registryType": "npm", "identifier": "@you/service-mcp", "version": "1.0.0", "transport": { "type": "stdio" } } ] } ``` For PyPI, use `registryType: "pypi"`; ownership is verified by an `mcp-name: <server-name>` line in the package README rather than a manifest field (see `modelcontextprotocol.io/registry/package-types` for the full per-registry verification rules). For a public hosted server, use a `remotes` array instead of `packages`: ```json { "remotes": [ { "type": "streamable-http", "url": "https://service.example.com/mcp" } ] } ``` `packages` and `remotes` can coexist so hosts choose. Verify after publish: ```bash curl "https://registry.modelcontextprotocol.io/v0.1/servers?search=io.github.you/service" ``` ## Just me Nothing to distribute. The server is already registered (see `references/deploy-local.md`). Confirm it works in a session and stop. -
node-sdk.md 1.9 KB
# Node / TypeScript (MCP SDK) quickstart Thin starter. For the full implementation guide (tool design, schemas, annotations, error handling, evaluation), invoke the `example-skills:mcp-builder` skill. Do not reimplement that material here. ## When to pick TypeScript - The wrapped service has a strong TypeScript/JavaScript SDK. - You will distribute via npm / `npx`. - Your team already maintains a Node toolchain. ## Minimal stdio server ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { z } from "zod"; const server = new McpServer({ name: "service-mcp", version: "1.0.0" }); server.registerTool( "service_search", { title: "Search service", description: "Search the service and return matching items.", inputSchema: { query: z.string(), limit: z.number().default(20) }, annotations: { readOnlyHint: true }, }, async ({ query, limit }) => ({ content: [{ type: "text", text: "..." }], }) ); const transport = new StdioServerTransport(); await server.connect(transport); ``` Switch to hosted HTTP at the end with `StreamableHTTPServerTransport`. The tools do not change. ## Conventions (mcp-builder owns the detail) - Use the modern `server.registerTool()` API (not the deprecated `server.tool()` / `setRequestHandler`). - Define inputs as Zod schemas; add `outputSchema` and return `structuredContent` for modern clients. - Set annotations: `readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`. - Build with `tsc` to `dist/index.js`; that file is the entry point. ## Packaging - Set `bin` in `package.json` so the server runs as `npx <package>`. - Dependencies: `@modelcontextprotocol/sdk`, `zod`. - Smoke-test with `npx @modelcontextprotocol/inspector`. See `references/deploy-local.md` for registration and `references/distribute-marketplace.md` for publishing to npm and the MCP registry. -
python-fastmcp.md 2.8 KB
# Python (FastMCP) quickstart Thin starter. For the full implementation guide (tool design, schemas, annotations, error handling, evaluation), invoke the `example-skills:mcp-builder` skill. Do not reimplement that material here. ## When to pick Python - The wrapped service has a clean Python SDK or is easy to call with `httpx`. - You want the fastest path to a working stdio server. - You will distribute via PyPI / `uvx`. ## Environment setup ```bash python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install "mcp[cli]" httpx pydantic ``` Use `.venv/bin/python` (or `.venv\Scripts\python.exe` on Windows) any time you reference Python directly so you stay inside the venv instead of the system interpreter. ## Minimal stdio server ```python from mcp.server.fastmcp import FastMCP mcp = FastMCP("service_mcp") @mcp.tool() async def service_search(query: str, limit: int = 20) -> str: """Search the service. Returns matching items as readable text.""" # call the service, format results return "..." if __name__ == "__main__": mcp.run() # stdio by default ``` Switch to hosted HTTP at the end with `mcp.run(transport="streamable_http", port=8000)`. The tools do not change. ## Conventions (mcp-builder owns the detail) - Validate inputs with Pydantic `BaseModel` + `Field(...)` constraints; set `ConfigDict(extra="forbid")`. - Return both a concise human-readable string and, where useful, structured data. - Add a `CHARACTER_LIMIT` guard and pagination (`limit`, `has_more`, `next_offset`) so large results do not flood context. - Never write logs to stdout on stdio (it corrupts the protocol stream); use stderr. - Read secrets from environment variables; validate on startup. ## Packaging - Define an entry point in `pyproject.toml` so the server runs as `uvx <package>`. - Dependencies: `mcp`, `httpx`, `pydantic`. - Build and smoke-test: `.venv/bin/python -m py_compile server.py`, then `npx @modelcontextprotocol/inspector`. - If the Inspector is blocked (SSL-restricted network, corporate proxy), fall back to manual JSON-RPC: pipe a JSON-RPC `initialize` + `tools/list` request to the server via stdin and confirm the response on stdout. Example: `echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}' | .venv/bin/python server.py`. - When registering a development server before packaging, use the full venv path so the subprocess inherits the right interpreter: `claude mcp add myserver -- /abs/path/to/.venv/bin/python server.py`. Bare `python` resolves to whatever is on `$PATH` at spawn time, which is usually not your venv. See `references/deploy-local.md` for registration and `references/distribute-marketplace.md` for publishing to PyPI and the MCP registry. -
scaling.md 5.3 KB
# Scale: operating a hosted MCP server Only substantive for the hosted-HTTP branch. For local/personal servers, scaling is N/A; the priorities there are maintainability and versioning, and you should skip to distribute. > There is no Anthropic-published "operate an MCP server in production" guide. This rests on the MCP spec (sessions, lifecycle, security best practices) plus normal infrastructure practice. Items not in the spec are marked as operator choices. ## Stateless vs session-bearing Statefulness is optional and controlled by the session-ID mechanism in Streamable HTTP: - A server **may** assign a session ID at initialization by returning an `Mcp-Session-Id` header on the `InitializeResult` response. It should be globally unique and cryptographically secure (UUID, JWT, or hash) and contain only visible ASCII. - If a session ID was issued, the client **must** send it on all subsequent requests. A server requiring it should answer requests without it (other than init) with `400 Bad Request`. - A server may terminate a session at any time; afterward it must answer that session ID with `404 Not Found`, and the client must start a new session with a fresh `InitializeRequest`. Scaling implication: if you issue **no** session ID, each request is independent and you can run N replicas behind a load balancer with no shared store. If you issue session IDs and hold in-memory session state, you need sticky sessions or a shared session store. The transport is per-request; the application layer still tracks negotiated protocol version, capabilities, and enabled tools, so "stateless" servers re-establish that cheaply per request rather than holding nothing. ## Resumability Servers may attach SSE `id` fields (a per-stream cursor, unique within the session); clients resume a dropped stream with the `Last-Event-ID` header on a GET. A server must not replay messages that belonged to a different stream. This lets a client survive a dropped connection or a replica restart without losing messages. ## Auth: OAuth 2.1 resource server For HTTP servers that need auth (stdio servers should use environment credentials instead): - The server is an OAuth 2.1 **resource server**. It must implement Protected Resource Metadata (RFC 9728) and, on 401, return a `WWW-Authenticate` header pointing at the resource-metadata URL. Discovery: 401 -> `/.well-known/oauth-protected-resource` -> authorization server metadata (RFC 8414) -> OAuth 2.1 flow with PKCE. - Clients must include the `resource` parameter (RFC 8707) set to your canonical server URI. - **Validate the token audience**: the server must verify access tokens were issued specifically for it. Invalid/expired -> 401; bad scopes -> 403; malformed -> 400. Bearer token on every request; never in the query string. - **Never pass tokens through.** The server must not accept tokens not issued for it, and when it calls an upstream API it acts as a separate OAuth client there with its own token. Passthrough breaks the audit trail and the trust boundary. ## Least-privilege scopes Do not advertise every scope or use wildcard/omnibus scopes (`*`, `all`, `full-access`). Start minimal and elevate incrementally via `WWW-Authenticate scope="..."` challenges. Log elevation events with correlation IDs. ## Session hijacking defense Servers that implement authorization must verify every inbound request and must not use sessions for authentication. Use non-deterministic (CSPRNG) session IDs, and bind them to user identity with a key like `<user_id>:<session_id>` so a guessed session ID cannot cross users. This matters specifically once you scale to multiple replicas. ## Timeouts Establish timeouts on all sent requests to prevent hung connections and resource exhaustion. Progress notifications may reset the clock, but always enforce a maximum timeout regardless. Note that Claude Code's per-tool `timeout` is a hard wall-clock limit that progress notifications do not extend. ## Versioning and tool changes - Protocol versions are date-stamped (`2024-11-05`, `2025-03-26`, `2025-06-18`), negotiated in `initialize`. If the server does not support the requested version it responds with one it does; the client disconnects if it cannot match. - Your server's own version is the free-form `serverInfo.version` string; semver is convention. - Tool-list changes are announced at runtime via the `tools.listChanged` capability and `notifications/tools/list_changed`. - There is **no spec-level tool-deprecation marker**. Adding tools or adding optional inputs is backward-compatible; removing tools or making optional inputs required is breaking. Deprecate by description plus a `list_changed` notification plus a server semver bump. ## Operator choices (not mandated by the spec) Rate limiting, caching, structured-logging backends, and metrics are not prescribed by MCP. Enforce rate limiting and request validation at the resource-server boundary (it depends on the token audience). The spec does define a server `logging` capability for emitting structured logs over the protocol. ## SSRF and external content If the server fetches external content: require HTTPS for metadata fetches, block private/reserved IP ranges (including cloud metadata `169.254.169.254`), and prefer an egress proxy over hand-rolled IP validation. Treat any externally fetched content as a prompt-injection risk. -
transports.md 2.2 KB
# Transports: stdio vs Streamable HTTP The MCP spec (current version 2025-06-18) defines two standard transports. SSE is deprecated. ## stdio The client launches the server as a subprocess and talks to it over stdin/stdout with newline-delimited JSON-RPC. The server may log to stderr but must write nothing else to stdout. Use stdio when: - The server runs on the user's own machine (personal tools, local data access). - Each user supplies their own credentials via environment variables. - You want the simplest possible setup and testing path. The spec says clients should support stdio whenever possible. Default to it for "just me" and org-local servers. Build and test on stdio even if the final target is hosted HTTP; the switch is a one-line transport change, not a rewrite. ## Streamable HTTP A single HTTP endpoint (for example `https://example.com/mcp`) that handles both POST and GET, optionally upgrading to an SSE stream for multi-message responses. This is the current recommended remote transport. It replaced the old HTTP+SSE transport from protocol version 2024-11-05. Use Streamable HTTP when: - One server serves many users (hosted/shared). - You want centralized credentials, auth, and updates. - The server needs to run somewhere always-on. Security requirements for HTTP servers (from the spec): - Validate the `Origin` header on all incoming connections (DNS-rebinding defense). - Bind to `127.0.0.1`, not `0.0.0.0`, when running locally. - Require authentication for anything non-public. - After initialization, clients must send the `MCP-Protocol-Version` header on every request; if absent the server assumes `2025-03-26`. ## The naming gotcha The same transport has two names depending on where you read: - Claude Code CLI and `.mcp.json` use `type: "http"` (and accept `streamable-http` as an alias). - The MCP spec and registry use `streamable-http`. They mean the same thing. When copy-pasting a config from either source, either spelling works in `.mcp.json`. ## SSE (deprecated) The old HTTP+SSE transport (protocol 2024-11-05). Kept only for backward compatibility. Do not build new servers on it. Claude Code's own docs warn to use HTTP servers instead where available.
-
-
SKILL.md 11.4 KB
--- name: build-mcp description: "Build an MCP server end to end, tailored to how it will be used. Use when asked to build an MCP, create an MCP server, wrap an API as a tool, make a tool for Claude, expose a service to an agent, build a Claude connector, or turn a service into MCP tools. Asks up front who the server is for (just me, my org, or public) and what it wraps, then walks through analyze, build, deploy, scale, and distribute with steps tailored to that answer. Builds on the example-skills:mcp-builder skill for implementation depth." --- # Build MCP Build a Model Context Protocol (MCP) server the right way, end to end. The defining move of this skill: establish the user's context with `AskUserQuestion` before building anything, then tailor every phase to that context. A personal local server and a public hosted server share almost no steps past "build", so branch early and commit to the branch. ## How this relates to mcp-builder The Anthropic `example-skills:mcp-builder` skill is the gold-standard reference for the *implementation* itself: FastMCP and TypeScript SDK patterns, tool design, input/output schemas, annotations, error handling, and evaluation. Do not duplicate it. This skill is the **scope-and-distribution wrapper around it**: it decides what to build, for whom, where it runs, and how it ships. When you reach the build phase, invoke `example-skills:mcp-builder` for the deep implementation guidance and keep this skill's references thin. ## The five phases 1. **Analyze**: understand the service to wrap and pick the right tool boundaries. 2. **Build**: scaffold and implement the server (delegates to mcp-builder). 3. **Deploy**: get it running and registered for the target runtime. 4. **Scale**: harden and operate it (only substantive for hosted servers). 5. **Distribute**: make it reachable by the intended audience. Run them in order. The `AskUserQuestion` answers from Phase 0 gate phases 3, 4, and 5. ## Phase 0: Establish context (AskUserQuestion, do this first) Before analyzing or writing anything, branch on the user's context. Ask the **audience** question first; it is the headline decision and it cascades into everything downstream. Then ask runtime only if it is still ambiguous, and ask language after Analyze (so you can recommend based on the wrapped service). **Question 1 (always, ask first): Audience / scope:** Use `AskUserQuestion`: - header: "Audience" - question: "Who is this MCP server for? This decides how we deploy and distribute it." - options: 1. "Just me": personal local tool on my machine. 2. "My team / org": shared internally, installed by colleagues. 3. "Public / external": published openly for anyone to install. **Question 2 (conditional): Where it runs:** Skip for "Just me" (assume local stdio). Ask for org/public when unclear: - header: "Runtime" - question: "Where should the server run?" - options: 1. "Local stdio": runs as a subprocess on each user's machine. Simplest. Each user supplies their own secrets. 2. "Hosted HTTP": one Streamable HTTP server many users connect to. Needs auth, deploy, and scaling. **Question 3 (after Analyze): Language:** - header: "Language" - question: "What should the server be written in?" - options: 1. "Python (FastMCP)": fastest path, great for wrapping Python-friendly APIs. 2. "Node / TypeScript (MCP SDK)": the mcp-builder ecosystem default (strongest SDK, models write TS well, best MCPB compatibility). Pick it when torn, or when the service has a strong TS SDK or you ship via npm. 3. "Recommend for me": pick based on the service analyzed in Phase 1; lean TypeScript unless the wrapped service is clearly Python-friendly. Ask one question at a time. Confirm the resolved context back to the user in one line before proceeding (e.g. "Building a personal, local, Python stdio server that wraps the Linear API"). That resolved tuple drives the branch table below. ## Branch table (the spine of this skill) | Phase | Just me (local stdio) | My org (local stdio) | My org (hosted HTTP) | Public (package) | Public (hosted HTTP) | |-------|----------------------|----------------------|----------------------|------------------|----------------------| | **Deploy** | `claude mcp add --scope user` or `.mcp.json` | Bundle in a Claude Code plugin; `${CLAUDE_PLUGIN_ROOT}` paths | Deploy Streamable HTTP endpoint + OAuth/bearer | Publish to PyPI/npm; users run via `uvx`/`npx` | Deploy HTTP endpoint; document the URL | | **Scale** | N/A (keep it maintainable) | N/A per-user; version the plugin | Real: statelessness, sessions, auth, rate limits | Versioning + backward-compat tool changes | Full: statelessness, auth, rate limits, observability | | **Distribute** | Not shared. Stop after registration. | Org marketplace (`.claude-plugin/marketplace.json` + `/plugin install`) | Org marketplace entry pointing at the hosted URL | PyPI/npm + MCP registry via `mcp-publisher` | MCP registry `remotes` entry + public docs | If a phase says N/A for the chosen branch, say so explicitly and move on. Do not pad it. Reference files for each branch: - **references/transports.md**: stdio vs Streamable HTTP, when each applies, the `http`/`streamable-http` naming gotcha. - **references/deploy-local.md**: `claude mcp add`, scopes, `.mcp.json`, Claude Desktop config, uvx/npx run configs. - **references/distribute-marketplace.md**: bundling an MCP server in a Claude Code plugin, org marketplace, the public MCP registry. - **references/scaling.md**: hosted-server statelessness, sessions, auth, versioning, security. - **references/python-fastmcp.md** and **references/node-sdk.md**: thin quickstarts that hand off to mcp-builder. Load only the references the current branch and phase need. Progressive disclosure. ## Phase 1: Analyze Understand what you are wrapping before you write tools. Output a short tool plan, then confirm it. 1. **Identify the service/API.** Read its docs or SDK. Note auth model (API key, OAuth, none), base URL, rate limits, pagination style. 2. **Pick tool boundaries.** This is a real tradeoff, framed the way mcp-builder frames it: comprehensive API coverage gives agents flexibility to compose operations, while specialized workflow tools are more convenient for specific tasks. Performance is client-dependent (some clients do better with code execution over basic tools, others with higher-level workflows). When uncertain, default to comprehensive API coverage rather than a few workflow tools. Either way each tool does one focused thing with a clear, action-oriented name. (mcp-builder has the full tool-design rubric; apply it here.) 3. **Decide read vs write.** Mark which tools are read-only and which mutate state; this becomes the `readOnlyHint` / `destructiveHint` annotations later. 4. **Scope the secrets.** What credentials does each tool need? For "Just me" they live in local env. For hosted, they live server-side and must never be passed through from the client (see scaling.md). 5. **Now ask the language question** (Phase 0 Q3) if it was deferred, recommending based on what you found. Deliverable: a numbered list of proposed tools, each with name, one-line purpose, inputs, read/write, and the service call it makes. Confirm with the user before building. ## Phase 2: Build Hand off to the implementation reference for the chosen language, which in turn defers to mcp-builder for depth. - Python: read **references/python-fastmcp.md**, then invoke `example-skills:mcp-builder` for the full FastMCP guide. - Node/TS: read **references/node-sdk.md**, then invoke `example-skills:mcp-builder` for the full TypeScript SDK guide. Build to the tool plan from Phase 1. Apply mcp-builder's rules: clear tool names, Pydantic/Zod input schemas with descriptions and constraints, structured + human-readable output, pagination with limits, actionable error messages, and tool annotations. Compile and test with the MCP Inspector (`npx @modelcontextprotocol/inspector`) before moving on. Then write and run mcp-builder's evaluation set: about 10 realistic, read-only, verifiable questions in its XML format, scored with its `scripts/evaluation.py` harness (e.g. `python scripts/evaluation.py -t stdio -c python -a server.py -o report.md evaluation.xml`). Do not hand-wave this; a server that the eval can't drive is not done. Start the server on **stdio** regardless of final runtime; it is the simplest thing to test locally. Switching to Streamable HTTP is a transport change at the end, not a rewrite (see transports.md). ## Phase 3: Deploy Branch on the resolved runtime. Read **references/deploy-local.md** for stdio, **references/transports.md** for HTTP. - **Local stdio (just me, or org-local):** register it. `claude mcp add --scope user <name> -- <command> <args>` for a personal server across all your projects, or a project-scoped `.mcp.json`. Verify with `claude mcp list` and `/mcp`. For org-local distribution, you do *not* register by hand on each machine; you bundle into a plugin (Phase 5). - **Hosted HTTP:** expose a single Streamable HTTP endpoint (POST+GET on one path). Validate the `Origin` header, bind to localhost when local, require auth. Connect with `claude mcp add --transport http <name> <url>` (add `--header "Authorization: Bearer ..."` for static tokens, or rely on the OAuth 401/`WWW-Authenticate` discovery flow). Containerize for repeatable deploys. ## Phase 4: Scale Only substantive for hosted HTTP servers. For local/personal servers, state plainly that scaling is N/A and that the priority is maintainability and versioning, then skip to Distribute. For hosted servers, read **references/scaling.md** and cover: stateless vs session-bearing design (`Mcp-Session-Id`), horizontal scaling, auth as an OAuth 2.1 resource server (validate token audience, never pass tokens through), least-privilege scopes, rate limiting, timeouts, observability, and protocol-version negotiation. Carry the caveat that there is no Anthropic-published "operate an MCP server" guide; this rests on the MCP spec plus normal infra practice. ## Phase 5: Distribute The payoff phase. Branch hard on the audience answer. Read **references/distribute-marketplace.md**. - **Just me:** nothing to distribute. The server is registered (Phase 3). Stop here; confirm it works in a session. - **My org / team:** package as a **Claude Code plugin** and list it in your org's `.claude-plugin/marketplace.json`. The plugin ships the server via an `mcpServers` key in `plugin.json` or a bundled `.mcp.json` (use `${CLAUDE_PLUGIN_ROOT}` for bundled paths). Colleagues run `/plugin marketplace add <org>/<repo>` then `/plugin install <name>@<marketplace>`. For auto-provisioning, add the marketplace to the project's `.claude/settings.json` under `extraKnownMarketplaces`. The TechWolf `ai-first-toolkit` repo is a working example of this layout. - **Public / external:** publish the package first (PyPI for Python, npm for Node), then register metadata with the **MCP registry** using the `mcp-publisher` CLI (`init` -> `login github` -> `publish`). For a hosted public server, register a `remotes` entry pointing at your URL instead of a package. Note the registry is in preview and its schema can change. You can do more than one (e.g. an org plugin *and* a public package). Distribution paths are additive. ## Done criteria - The server compiles, the Inspector lists the tools, and the evaluation set passes. - It is registered or published for the resolved audience, and you verified it loads in a real Claude session. - The user can name how a colleague (or the public) would install it, matching their audience answer.
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.