FMTechnical notes
Portfolio
Back to the blog

AI & Agents · Advanced · Agentic

MCP for real: resources, prompts, writes, and the HTTP transport

Part one solved read-only tools. Part two solves what actually hurts in production: what to expose as data, how to write without breaking anything, and how to serve the server to several clients over HTTP.

After reading this
  • Choose between tool, resource, and prompt without guessing
  • Expose data with a ResourceTemplate and a list callback
  • Design a write with dry-run, idempotency, and an audit log
  • Serve the same server over HTTP with auth and limits
  • Test the whole protocol with a real client
01 / 06

Three primitives, one rule

The usual confusion is putting everything into tools. A tool is an action the model decides to run; a resource is data the host attaches to context; a prompt is a template a person chooses.

The rule I use: if the result changes the system state, it is a tool. If it is stable information worth having at hand, it is a resource. If it is a way to ask for work, it is a prompt.

  • Tool: a verb, with effects and validation.
  • Resource: a noun, with a URI and a mimeType.
  • Prompt: a template with arguments, chosen by the person.
02 / 06

Resources and templates

A resource is identified by URI. If the set is finite and enumerable, the list callback makes it visible in resources/list; if it is unbounded, register it with list: undefined and resolve it on demand.

The callback receives the URI and the parsed variables. That is where you apply the path guard again: coming from the protocol does not make it trustworthy.

ts
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/server";

const server = new McpServer({ name: "repo", version: "1.0.0" });

server.registerResource(
  "readme",
  "repo://README.md",
  { title: "Repository readme", mimeType: "text/markdown" },
  async (uri) => ({
    contents: [{ uri: uri.href, text: await readText("README.md") }],
  }),
);

server.registerResource(
  "source-file",
  new ResourceTemplate("repo://{path}", {
    list: async () => ({
      resources: [
        { uri: "repo://src/app/page.tsx", name: "Home page" },
        { uri: "repo://src/lib/seo.ts", name: "SEO helpers" },
      ],
    }),
  }),
  { title: "Source file", mimeType: "text/plain" },
  async (uri, { path }) => ({
    contents: [{ uri: uri.href, text: await readInsideRoot(path) }],
  }),
);
03 / 06

Prompts with arguments

A prompt executes nothing: it builds a message. It lets a person choose a proven flow instead of typing the same request every time.

Arguments are validated with Zod and their descriptions travel in prompts/list, so the client can render them as a form.

ts
import * as z from "zod/v4";

server.registerPrompt(
  "review-change",
  {
    title: "Review a change",
    description: "Review a diff against the repository conventions",
    argsSchema: z.object({
      diff: z.string().describe("Unified diff to review"),
      focus: z.enum(["security", "performance", "readability"]).optional(),
    }),
  },
  ({ diff, focus = "readability" }) => ({
    messages: [
      {
        role: "user",
        content: {
          type: "text",
          text: "Review this diff with a " + focus + " focus:\n\n" + diff,
        },
      },
    ],
  }),
);
04 / 06

The dangerous half: writes

A write tool is the difference between an assistant and an incident. A safe design has four pieces: dry-run by default, an idempotency key, explicit limits, and a log of what happened.

The dry-run returns the proposed change without applying it. The idempotency key stops a host retry from duplicating the operation. Limits bound the possible damage. The log lets you reconstruct what the agent did and with which arguments.

ts
server.registerTool(
  "write_file",
  {
    title: "Write a file",
    description:
      "Replace a file inside the workspace. Defaults to a dry run; pass dryRun: false to apply.",
    inputSchema: z.object({
      path: z.string().describe("Repository-relative path"),
      content: z.string().max(200_000),
      dryRun: z.boolean().default(true),
      idempotencyKey: z.string().uuid(),
    }),
    annotations: {
      readOnlyHint: false,
      destructiveHint: true,
      idempotentHint: true,
    },
  },
  async ({ path: relative, content, dryRun, idempotencyKey }) => {
    const target = resolveInsideRoot(relative);

    if (seen.has(idempotencyKey)) {
      return { content: [{ type: "text", text: "Already applied." }] };
    }
    if (dryRun) {
      return {
        content: [
          {
            type: "text",
            text: "Would write " + content.length + " bytes to " + relative,
          },
        ],
      };
    }

    seen.add(idempotencyKey);
    await writeFile(target, content, "utf8");
    console.error("write_file", { path: relative, bytes: content.length });
    return { content: [{ type: "text", text: "Written: " + relative }] };
  },
);
05 / 06

From stdio to HTTP

stdio is for a local process. If the server must serve several clients, or live outside the user's machine, it goes over HTTP with the streamable transport.

The simplest example is stateless: one server and one transport per request. With sessions, one transport is created per initialize and routed by the Mcp-Session-Id header.

  • Auth before creating the transport: one token per client, never one shared global token.
  • Session and body-size limits; an open server is saturated with initialize.
  • Close transports on shutdown so no stream is left hanging.
ts
import { createMcpExpressApp } from "@modelcontextprotocol/express";
import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node";
import { McpServer } from "@modelcontextprotocol/server";

const app = createMcpExpressApp();

app.post("/mcp", async (req, res) => {
  if (req.headers.authorization !== "Bearer " + process.env.MCP_TOKEN) {
    res.status(401).json({ error: "unauthorized" });
    return;
  }

  const server = buildServer();
  const transport = new NodeStreamableHTTPServerTransport({
    sessionIdGenerator: undefined,
  });

  await server.connect(transport);
  await transport.handleRequest(req, res, req.body);
});
06 / 06

Testing the whole protocol

Testing the handler in isolation is fine, but it does not test the contract: tool names, schemas, and responses. For that you connect a real client over an in-memory transport.

That test runs in milliseconds, without a model or network, and fails when someone renames a tool or changes a description the model uses to choose it.

ts
import { Client } from "@modelcontextprotocol/client";
import { InMemoryTransport } from "@modelcontextprotocol/client";

async function connect(server: McpServer) {
  const client = new Client({ name: "test", version: "1.0" });
  const [clientEnd, serverEnd] = InMemoryTransport.createLinkedPair();
  await Promise.all([client.connect(clientEnd), server.connect(serverEnd)]);
  return client;
}

test("the tool list is the contract", async () => {
  const client = await connect(buildServer());
  const { tools } = await client.listTools();
  expect(tools.map((tool) => tool.name)).toEqual(["read_file", "write_file"]);
});

test("a path outside the workspace is refused", async () => {
  const client = await connect(buildServer());
  const result = await client.callTool({
    name: "read_file",
    arguments: { path: "../secrets.env" },
  });
  expect(result.isError).toBe(true);
});
Component tree● interactive

Layout-level composition. Owns the document structure and orchestrates which features render.

Practice

Turn a write into a safe operation

Add a write tool to your server with dry-run by default, an idempotency key, and an audit log. Write two tests: one that verifies nothing changes without dryRun: false, and one that verifies the same key does not duplicate.

Show a hint

If the idempotency test passes with different keys, it is not testing idempotency.