In this tutorial we build a Model Context Protocol (MCP) server that lets an AI client search a local issue tracker, close an issue after the user confirms, and read a summary. The same code runs over stdio and Streamable HTTP, and a small client script tests both.
Checked on December 4, 2026 with Node.js 24.23.0, @modelcontextprotocol/server 2.4.0, @modelcontextprotocol/client 2.4.0, @modelcontextprotocol/node 2.1.2, Zod 4.6.7, TypeScript 7.0.2 and MCP Inspector 2.17.0. The current spec revision is 2026-07-28.
What changed since older tutorials
Many tutorials use @modelcontextprotocol/sdk, which is version 1. The official TypeScript SDK now ships v2 as separate packages for servers, clients and runtime adapters. Version 1 gets fixes for at least six months after the v2 release on July 27, 2026, but if you have a v1 server, use the upgrade guide rather than mixing the two APIs.
The protocol changed too. Revision 2026-07-28 removed the initialize handshake and HTTP sessions, so each request now carries its own version and client capabilities. The old HTTP+SSE transport is deprecated. Use stdio for a local process and Streamable HTTP for a network endpoint. In the v2 SDK, serveStdio and createMcpHandler also answer older clients by default.
Set up the project
Create the project folder and install the v2 server, client and Node packages:
mkdir issues-mcp && cd issues-mcp
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/server@2 @modelcontextprotocol/node@2 @modelcontextprotocol/client@2 zod
npm install -D typescript @types/node
mkdir src
Node 24 can run erasable TypeScript directly, so there's no build step, but Node doesn't check the types. Add this tsconfig.json so npx tsc can do that (erasableSyntaxOnly needs TypeScript 5.8 or later):
{
"compilerOptions": {
"target": "ES2023",
"module": "nodenext",
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"types": ["node"]
},
"include": ["src"]
}
Add the data source
Create src/db.ts. It uses the built-in node:sqlite module, which is a release candidate in Node 24. Node 22.23.5 also ran the project, with an experimental warning.
import { join } from 'node:path'
import { DatabaseSync } from 'node:sqlite'
const file = process.env.ISSUES_DB ?? join(import.meta.dirname, '../issues.db')
const db = new DatabaseSync(file)
db.exec(`
CREATE TABLE IF NOT EXISTS issues (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('open', 'closed'))
);
INSERT OR IGNORE INTO issues (id, title, status) VALUES
(1, 'Login form loses focus on error', 'open'),
(2, 'CSV export drops the last row', 'open'),
(3, 'Login redirect ignores query string', 'closed');
`)
export type Issue = { id: number; title: string; status: 'open' | 'closed' }
export function searchIssues(query: string, limit: number) {
return db
.prepare('SELECT id, title, status FROM issues WHERE instr(lower(title), lower(?)) > 0 ORDER BY id LIMIT ?')
.all(query, limit) as Issue[]
}
export function getIssue(id: number) {
return db.prepare('SELECT id, title, status FROM issues WHERE id = ?').get(id) as Issue | undefined
}
export function closeIssue(id: number) {
return db.prepare("UPDATE issues SET status = 'closed' WHERE id = ? AND status = 'open'").run(id).changes === 1
}
export function countByStatus() {
return db.prepare('SELECT status, COUNT(*) AS total FROM issues GROUP BY status ORDER BY status').all()
}
Every value is a bound parameter, and the module exposes four narrow functions. There's no run_sql tool, because then any instruction that reaches the model could become a query.
Define the tools and resource
Create src/server.ts. It registers two tools, search_issues and close_issue, and one read-only resource, issues://summary. They're wrapped in a createServer factory because the HTTP transport calls it for every request:
import { acceptedContent, inputRequired, inputResponse, McpServer } from '@modelcontextprotocol/server'
import type { CallToolResult, InputRequiredResult } from '@modelcontextprotocol/server'
import * as z from 'zod'
import { closeIssue, countByStatus, getIssue, searchIssues } from './db.ts'
const issueSchema = z.object({
id: z.number().int(),
title: z.string(),
status: z.enum(['open', 'closed']),
})
const confirmSchema = z.object({ confirm: z.boolean() })
const failure = (text: string): CallToolResult => ({
content: [{ type: 'text', text }],
isError: true,
})
export function createServer() {
const server = new McpServer({ name: 'issues', version: '1.0.0' })
server.registerTool(
'search_issues',
{
description: 'Find issues whose title contains the query text.',
inputSchema: z.object({
query: z.string().trim().min(2).max(100),
limit: z.number().int().min(1).max(20).default(10),
}),
outputSchema: z.object({ issues: z.array(issueSchema) }),
annotations: { readOnlyHint: true },
},
async ({ query, limit }) => {
const output = { issues: searchIssues(query, limit) }
return {
content: [{ type: 'text', text: JSON.stringify(output) }],
structuredContent: output,
}
}
)
server.registerTool(
'close_issue',
{
description: 'Close one open issue. The user is asked to confirm first.',
inputSchema: z.object({ id: z.number().int().positive() }),
annotations: { destructiveHint: true, idempotentHint: true },
},
async ({ id }, ctx): Promise<CallToolResult | InputRequiredResult> => {
const issue = getIssue(id)
if (!issue) return failure(`No issue ${id}. Use search_issues to find a valid id.`)
if (issue.status === 'closed') return failure(`Issue ${id} is already closed.`)
const answers = ctx.mcpReq.inputResponses
const view = inputResponse(answers, 'confirm')
if (view.kind === 'missing') {
return inputRequired({
inputRequests: {
confirm: inputRequired.elicit({
message: `Close issue ${id}, "${issue.title}"?`,
requestedSchema: confirmSchema,
}),
},
})
}
const confirmed = acceptedContent(answers, 'confirm', confirmSchema)
if (confirmed?.confirm !== true) return failure('The user did not confirm. Nothing changed.')
closeIssue(id)
return { content: [{ type: 'text', text: `Closed issue ${id}.` }] }
}
)
server.registerResource(
'summary',
'issues://summary',
{ description: 'Issue totals by status', mimeType: 'application/json' },
async (uri) => ({
contents: [{ uri: uri.href, mimeType: 'application/json', text: JSON.stringify(countByStatus()) }],
})
)
return server
}
A tool is an action the model can choose to call. A resource is read-only data the client application can list and load. The summary is a resource because a client might attach it as context without a model deciding to call anything.
The SDK checks inputSchema before your handler runs. A bad argument comes back as a tool result with isError: true, so the model can read the message and try again. The expected failures in close_issue use the same shape. If the Zod part is new to you, structured outputs with Zod uses the same kind of schema.
Return both content and structuredContent from search_issues. The docs on the SDK's main branch say content may be omitted when there is an output schema, but that doesn't type-check with the published 2.4.0 package. If you run it anyway, clients get an empty content array.
Asking before a write
close_issue runs twice. On the first call it changes nothing and returns inputRequired(...), so the client shows the question and retries the call with an answer. The second run looks the issue up again, validates the answer with acceptedContent, then updates the row. The input-required guide covers the pattern.
The answer comes from the client, so it guards against a model acting too fast. It doesn't prove who the user is or what they may do, and a hostile client can send confirm: true. Any server with more than one user needs its own permission check inside the tool.
The annotations are hints as well. The spec tells clients to treat them as untrusted unless the server is trusted.
Serve it over stdio
For a local client, the whole entry point is two calls. Create src/stdio.ts:
import { serveStdio } from '@modelcontextprotocol/server/stdio'
import { createServer } from './server.ts'
serveStdio(createServer)
console.error('issues server ready on stdio')
On stdio, stdout carries the JSON-RPC messages, so log with console.error. A single console.log puts a line in the stream that the client can't parse.
Serve it over Streamable HTTP
The HTTP entry point wraps the same factory in a request handler. Create src/http.ts:
import { createServer as createHttpServer } from 'node:http'
import { localhostHostValidation, localhostOriginValidation, toNodeHandler } from '@modelcontextprotocol/node'
import { createMcpHandler } from '@modelcontextprotocol/server'
import { createServer } from './server.ts'
const handler = toNodeHandler(createMcpHandler(createServer))
const validHost = localhostHostValidation()
const validOrigin = localhostOriginValidation()
createHttpServer((req, res) => {
if (!validHost(req, res) || !validOrigin(req, res)) return
if (req.url?.split('?')[0] !== '/mcp') {
res.writeHead(404).end()
return
}
void handler(req, res)
}).listen(3000, '127.0.0.1', () => {
console.log('issues server on http://127.0.0.1:3000/mcp')
})
createMcpHandler calls createServer for every HTTP request, so keep state in the database rather than the factory. The SQLite connection opens at module scope, so it's shared across requests.
The handler does not check Host, Origin or tokens. The localhostHostValidation and localhostOriginValidation guards block DNS rebinding, where a web page tries to reach a server on your machine. With the server running, requests that send Origin: https://evil.example or Host: evil.example get a 403.
This file is for one machine and one user. Before you bind it to a public address, add TLS, replace the localhost-only guards with your real hostnames, and add authorization.
Test it with a client
This script connects over either transport, calls both tools, answers the confirmation question and reads the resource. Create src/check.ts:
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio'
const client = new Client(
{ name: 'check', version: '1.0.0' },
{ capabilities: { elicitation: { form: {} } }, versionNegotiation: { mode: 'auto' } }
)
client.setRequestHandler('elicitation/create', async (request) => {
console.log('asked:', request.params.message)
return { action: 'accept', content: { confirm: process.argv[3] === 'yes' } }
})
await client.connect(
process.argv[2] === 'http'
? new StreamableHTTPClientTransport(new URL('http://127.0.0.1:3000/mcp'))
: new StdioClientTransport({ command: process.execPath, args: ['src/stdio.ts'] })
)
console.log('era:', client.getProtocolEra())
console.log('tools:', (await client.listTools()).tools.map((t) => t.name))
const call = async (name: string, args: Record<string, unknown>) =>
console.log(name, JSON.stringify(await client.callTool({ name, arguments: args })))
await call('search_issues', { query: 'login' })
await call('search_issues', { query: 'x' })
await call('close_issue', { id: 2 })
const summary = await client.readResource({ uri: 'issues://summary' })
console.log('summary:', JSON.stringify(summary.contents))
await client.close()
Run the type check, then decline and accept the write over stdio:
npx tsc
node src/check.ts stdio no
node src/check.ts stdio yes
This is the output of the last command, shortened to the relevant fields:
era: modern
tools: [ 'search_issues', 'close_issue' ]
search_issues ... "structuredContent":{"issues":[{"id":1,...},{"id":3,...}]}
search_issues ... "Input validation error: Invalid arguments for tool search_issues: query: Too small: expected string to have >=2 characters" ... "isError":true
asked: Close issue 2, "CSV export drops the last row"?
close_issue ... "Closed issue 2."
summary: ... [{"status":"closed","total":2},{"status":"open","total":1}]
With no, the tool returned The user did not confirm. Nothing changed. and the summary still had two open issues. Delete issues.db to reset the data, since a second accepted run reports that the issue is already closed.
For HTTP, run node src/http.ts in one terminal and node src/check.ts http yes in another. The results matched.
versionNegotiation: { mode: 'auto' } is needed here because the v2 client still defaults to the older handshake. era: modern confirms the 2026-07-28 protocol is in use.
Check older clients
With mode: 'legacy', search and the resource work on both transports, and confirmation works over stdio. Over HTTP, the per-request legacy path can't send a question back to the client, so close_issue returns an error and leaves the row alone. A modern client with no elicitation support is also refused. Failing closed is what you want, but tell users which clients can close issues.
Use the Inspector
The official MCP Inspector has a web UI and a scriptable mode:
npx @modelcontextprotocol/inspector@2.17.0 node src/stdio.ts
npx @modelcontextprotocol/inspector@2.17.0 --cli node src/stdio.ts --method tools/list
npx @modelcontextprotocol/inspector@2.17.0 --cli node src/stdio.ts \
--method tools/call --tool-name search_issues --tool-arg query=login
The CLI lists both tools, returns issues 1 and 3 for login, and can read the resource. A plain CLI call to close_issue is refused because it doesn't offer elicitation. Inspector 2.17.0 declares support for patched Node 22, 24 and 26 releases, and not Node 25. It starts the server with whichever node comes first on your PATH, so make sure that's the version you expect or pass "$(which node)" from a shell that has it.
Register the server
Use an absolute path, because clients do not all start servers from your project directory. For Claude Code:
claude mcp add issues -- node /absolute/path/issues-mcp/src/stdio.ts
claude mcp get issues
Claude Code 2.1.333 reported this server as connected. Add --scope project before the -- to write a shared .mcp.json instead. Teammates have to approve a project server before it runs.
VS Code now documents workspace-root .mcp.json for its Copilot harness, and says new setups should not use .vscode/mcp.json, which belongs to the deprecated Local harness (configuration reference):
{
"mcpServers": {
"issues": {
"type": "stdio",
"command": "node",
"args": ["/absolute/path/issues-mcp/src/stdio.ts"],
"tools": ["*"]
}
}
}
That shape follows the VS Code docs and has not been run in VS Code. The tools field is documented by VS Code and isn't needed by Claude Code, which matters if a team shares one .mcp.json. Replace * with tool names to limit what the agent sees. If the client was launched from a desktop icon and can't find node, use the full path to the Node binary.
What not to expose
- Don't return environment variables, tokens or connection strings from a tool or resource. Tool output goes to the client and can reach the model provider, so put credentials in the server's environment and keep them out of shared config.
- Avoid raw SQL, shell commands and arbitrary file paths. Offer one operation with one schema, because a local server runs with your user account's permissions.
- Require a confirmation, plus a server-side permission check, for deletes, payments and messages.
- An issue title may contain instructions written for the model. Return it as data, limit its size, and don't give the same agent powerful unrelated tools without review.
The spec requires servers to validate inputs, control access, rate limit tool calls and sanitize output. This example validates inputs and limits result size, so add rate limits and access control before it has a second user. Read the MCP security guide next.
Stateless MCP and stateless agents
The HTTP server in src/http.ts is already stateless. In the 2026-07-28 spec, every request carries its protocol version and client capabilities in _meta, and Streamable HTTP mirrors Mcp-Method, Mcp-Name and MCP-Protocol-Version into HTTP headers for routing. There is no initialize handshake and no Mcp-Session-Id.
That is why createMcpHandler(createServer) runs createServer per request and holds nothing in memory between calls. Its handler.fetch is a standard (Request) => Promise<Response>, so the same factory mounts on Node via toNodeHandler or on Cloudflare Workers, Deno or Bun with export default handler. The factory also receives { era, authInfo, requestInfo } so you can verify bearer tokens in middleware and scope each request to its caller.
Multi-step confirmation works without server sessions too. On the first call, close_issue mutates nothing and returns input_required; the second call can land on a different process, re-reads the issue, checks inputResponses and updates the row only if it is still open. That pattern works because the database holds the state and the write is safe to retry.
Stateless servers simplify agent infrastructure as well:
- No sticky sessions or reconnect choreography. An agent loop running in a serverless function, queue worker or load-balanced service can send each tool call to any healthy replica without keeping an HTTP session alive.
- Agent state stays in the agent. Conversation history, retry state and checkpoints live in your agent's own store instead of tying agent lifetime to an MCP transport connection.
- Cross-call state uses explicit handles. If a workflow spans multiple tool calls, return an explicit server-minted ID (such as a draft or job ID) from the first tool and accept it as an argument on the next one.
Stateless HTTP has tradeoffs. SQLite on local disk only works on one machine, so multi-node deployments need a shared database. An ordinary HTTP tool request also cannot receive unsolicited server push notifications; if clients need change events, the 2026-07-28 spec uses an opt-in subscriptions/listen POST stream, and across multiple nodes SDK v2 needs a shared ServerEventBus (for example over Redis) passed via createMcpHandler(createServer, { bus }) (scaling guide). Without push streams, agents poll or use the optional io.modelcontextprotocol/tasks extension.
Code Mode: when an agent has too many tools
Direct tool calling fits a two-tool server like issues, but it degrades as an agent connects to more servers. Every tool's schema takes prompt tokens before the user's request is even read, and every intermediate tool result travels back through the model on each turn.
Code Mode (also described as code execution with MCP) flips that loop. Instead of exposing dozens or hundreds of raw tool definitions to the model, the runtime converts MCP tool schemas into typed TypeScript functions inside a sandbox and gives the model one code-execution tool (or a search and execute pair for large catalogs). The model writes a short script that discovers tools, loops over results, filters data inside the sandbox and returns only the final summary.
Both Cloudflare and Anthropic documented this pattern:
- In Cloudflare's Code Mode MCP server for the Cloudflare API, replacing individual endpoint tools with
search()andexecute()dropped tool-definition overhead from 1.17 million tokens to about 1,000 tokens (measured withtiktoken). Cloudflare exposes the same pattern in its experimental@cloudflare/codemodepackage. - In Anthropic's Google Drive and Salesforce example, exposing MCP tools as TypeScript modules so the agent loads only the files it needs cut context usage from 150,000 tokens to 2,000 tokens, while keeping large intermediate documents out of the model's context window.
To see how this changes the call pattern, here is an illustrative sketch (not executed against a Code Mode runtime here) of what a model writes against typed bindings generated from our issues server when asked to triage several keywords at once:
// Illustrative script generated by an agent inside a Code Mode sandbox
const terms = ['login', 'csv', 'timeout']
const openById = new Map<number, { id: number; title: string }>()
for (const query of terms) {
const { issues } = await codemode.search_issues({ query, limit: 20 })
for (const issue of issues) {
if (issue.status === 'open') openById.set(issue.id, { id: issue.id, title: issue.title })
}
}
return [...openById.values()]
With direct tool calls, that triage takes three round trips through the model and puts every closed or duplicate row into the prompt. In Code Mode, the sandbox runs the loop once and returns only the deduplicated open issues.
When to use Code Mode, and how to sandbox it
Stick with direct MCP tool calls when you have a small, fixed set of tools like issues, straightforward single-step calls or no appetite for operating a sandbox. Code Mode pays off when an agent spans dozens or hundreds of tools, filters large payloads or runs multi-step loops and joins.
Never execute model-written code with eval() or new Function() in your host Node.js process. Run it in an isolated sandbox with strict CPU, memory and timeout limits and no direct network access, such as disposable V8 isolates (Cloudflare's Dynamic Worker Loader), containers or microVMs. Keep API tokens outside the sandbox in host-managed bindings so generated code can call a tool without ever reading its credentials.
Code Mode also does not replace server-side boundaries. Keep narrow tool schemas, input validation and permission checks on the MCP server itself, and gate destructive writes like close_issue behind explicit approval (for instance, keeping write tools direct or marking them requiresApproval: true in an adapter such as @cloudflare/codemode's McpConnector).
Choosing a transport, or skipping MCP
Use stdio when the data and the AI client run on the same machine. Use stateless Streamable HTTP when several clients or scaled agent workers need one endpoint and you are ready to run authentication and shared storage.
Start with direct tool calls while your tool count is small, and add Code Mode only when tool schemas or intermediate payloads start crowding the context window. If only your own app calls the function, you may not need MCP at all: the AI SDK tool calling example has less to operate.
References
- MCP specification 2026-07-28 (changelog)
- MCP TypeScript SDK v2 docs (sessions, state and scaling)
- MCP security best practices
- Cloudflare: Code Mode, the better way to use MCP and give agents an entire API in 1,000 tokens
- Cloudflare Agents docs: Code Mode
- Anthropic: Code execution with MCP for efficient agents
Related articles
Build your own coding-agent benchmark in Node.js
Build a small coding-agent benchmark in Node.js with disposable git worktrees, hidden verifiers, time limits, repeated runs and Wilson intervals.
Migrate to Vercel AI SDK 7: a tool-calling guide
Move a tool-calling app from Vercel AI SDK 6 to 7: what breaks, what the codemod misses, a before/after agent, and the new features worth adopting.
What an AI coding model costs per solved task
Turn per-million-token prices into cost per attempt and cost per solved task with small JavaScript functions, including caching, retries and review time.

