# How MCPs Actually Works

I wire AI agents into production systems for work. The annoying part is never the agent logic itself. It's the glue: every LLM provider has a different function-calling format, every agent framework invents its own tool abstraction, and you end up writing adapters on top of adapters.

Anthropic's [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) is an attempt to fix this, and after building a few servers with it, I think it mostly works.

**TL;DR:** MCP is an open protocol that standardizes how AI models discover and call external tools. Below, I build a working MCP server in TypeScript, explain the three primitives (tools, resources, prompts), and go through the gotchas I ran into.

## What MCP actually does

Say you want Claude to query your database, pull files from S3, and check CI status. Without MCP, you write tool definitions for each integration, wire up auth, and hope the JSON schema matches what the model expects. Three integrations, three separate plumbing jobs.

MCP inverts the direction. The *server* advertises what it can do, and the client (Claude, or any MCP-compatible host) discovers those capabilities at runtime over a standard JSON-RPC transport.

The architecture:

![mcp-client-server-architecture](https://cdn.hashnode.com/uploads/covers/66967e4279fcd6178ebdfd49/8c89ad70-00fe-46d4-a5f5-5ab8f589cd2d.png align="center")

Each server is a separate process. They communicate over stdio (local) or SSE over HTTP (remote). The host doesn't need to know anything about the servers ahead of time.

## The three primitives

![mcp-primitives](https://cdn.hashnode.com/uploads/covers/66967e4279fcd6178ebdfd49/4dc5b481-505c-4cf4-a1e8-09927579c3bb.png align="center")

A server can expose three things:

1. **Tools** -- functions the model can call. `query_database(sql)`, `create_ticket(title, body)`, that sort of thing. The model decides when to invoke them.
2. **Resources** -- read-only data the model can pull in for context. `file://config.yaml` or `postgres://users/schema`. The user or client controls when these get attached.
3. **Prompts** -- reusable prompt templates with arguments. User-triggered, not model-triggered.

You'll mostly use tools. That's what I'll focus on.

## Building a server

I'll build an MCP server that wraps a REST API. Weather API as the example, because it keeps the focus on MCP mechanics instead of business logic.

Scaffold the project:

```bash
mkdir weather-mcp-server && cd weather-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node
npx tsc --init
```

The `@modelcontextprotocol/sdk` package is the official TypeScript SDK. `zod` handles input validation, and the SDK uses it internally for schema generation.

Now the server itself. Create `src/index.ts`:

```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: "weather",
  version: "1.0.0",
});

server.tool(
  "get_forecast",
  "Get the weather forecast for a city",
  {
    city: z.string().describe("City name, e.g. 'Mumbai'"),
    days: z
      .number()
      .min(1)
      .max(7)
      .default(3)
      .describe("Number of days to forecast"),
  },
  async ({ city, days }) => {
    const API_KEY = process.env.WEATHER_API_KEY;
    if (!API_KEY) {
      return {
        content: [
          {
            type: "text",
            text: "WEATHER_API_KEY environment variable is not set.",
          },
        ],
        isError: true,
      };
    }

    const url = `https://api.weatherapi.com/v1/forecast.json?key=${API_KEY}&q=${encodeURIComponent(city)}&days=${days}`;
    const res = await fetch(url);

    if (!res.ok) {
      return {
        content: [
          { type: "text", text: `API error: ${res.status} ${res.statusText}` },
        ],
        isError: true,
      };
    }

    const data = await res.json();
    const forecast = data.forecast.forecastday.map((day: any) => ({
      date: day.date,
      condition: day.day.condition.text,
      high_c: day.day.maxtemp_c,
      low_c: day.day.mintemp_c,
      rain_chance: day.day.daily_chance_of_rain,
    }));

    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(forecast, null, 2),
        },
      ],
    };
  }
);

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
}

main().catch(console.error);
```

That's the whole server. The pieces worth noting:

`McpServer` handles protocol negotiation and request routing. You never write JSON-RPC by hand.

`server.tool(name, description, schema, handler)` registers a tool. The schema uses Zod; the SDK converts it to JSON Schema for the client. The handler returns `content` blocks (text, images, embedded resources) with an optional `isError` flag.

`StdioServerTransport` talks over stdin/stdout, which is what Claude Code and Claude Desktop use for local servers. For remote deployment, you'd swap it for an HTTP transport.

Here's the full lifecycle of a tool call, from connection to response:

![](https://cdn.hashnode.com/uploads/covers/66967e4279fcd6178ebdfd49/2d24c18b-fb17-457f-ae2e-6519b2041ef2.png align="center")

Compile and test:

```bash
npx tsc
printf '{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0.0"}}}\n{"jsonrpc":"2.0","id":1,"method":"tools/list"}\n' | node dist/index.js
```

You should see two JSON responses: the initialize handshake, then your tool's name, description, and input schema.

## Hooking it into Claude

To use this with Claude Code, add a server entry to your Claude config. Create or edit `.claude/settings.json`:

```json
{
  "mcpServers": {
    "weather": {
      "command": "node",
      "args": ["/absolute/path/to/weather-mcp-server/dist/index.js"],
      "env": {
        "WEATHER_API_KEY": "your-api-key-here"
      }
    }
  }
}
```

Restart Claude Code. It picks up the server, reads its tool list, and `get_forecast` shows up as a callable tool. No plugin system, no marketplace.

For Claude Desktop, same format, different file: `claude_desktop_config.json` (location depends on OS).

## Adding a resource

Tools are model-triggered. Resources are for context the user or client attaches. Here's an example that exposes a resource:

```typescript
server.resource(
  "api-status",
  "weather://api-status",
  { mimeType: "application/json" },
  async () => ({
    contents: [
      {
        uri: "weather://api-status",
        text: JSON.stringify({
          provider: "WeatherAPI",
          plan: "free",
          calls_today: 142,
          limit: 1000,
        }),
      },
    ],
  })
);
```

When a user asks "how many API calls have I used today?", they can attach this resource to give Claude the context to answer, without the model needing to call a tool.

## Gotchas

**Stdio and console.log don't mix.** `console.log` writes to stdout, which is the same channel MCP uses for JSON-RPC. Your debug output will corrupt the protocol stream and kill the connection. Use `console.error`, or write to a file.

**Zod version mismatches.** The SDK ships its own Zod. If your project pins a different version, you'll get confusing schema validation failures. Stick to the same major version the SDK uses.

**Unhandled throws crash the server.** If your tool handler throws, the whole process dies and the client loses the connection. Catch errors and return them as `isError: true` content blocks instead. Claude handles error responses well and usually explains the failure or retries.

**Vague tool descriptions cause misfires.** Claude picks tools based on name and description. "Does weather stuff" will get invoked at the wrong times. Write something specific: "Get the weather forecast for a city, returning temperature highs/lows and rain probability for 1-7 days."

**Transport is a deployment choice.** Stdio works locally. For a shared server, you want HTTP. The SDK supports both, but remote servers need their own auth layer since MCP doesn't handle authentication.

## Where things stand

The [official registry](https://github.com/modelcontextprotocol/servers) lists thousands of community-built servers. Anthropic open-sourced reference implementations for filesystem, GitHub, Slack, PostgreSQL, and a few others.

The spec is still moving. Recent changes include streamable HTTP transport (replacing the older SSE-only approach), structured tool output types, and better capability negotiation. If you're building production servers, keep an eye on the [spec changelog](https://modelcontextprotocol.io/specification).

The thing I like most about MCP is the composability. Each server is a self-contained capability boundary. You can combine a database server, a filesystem server, and your business logic server, and the model coordinates between them. That's a much cleaner separation than one giant tool definition that does everything.

## Getting started fast

The quickest path:

```bash
npx @anthropic-ai/create-mcp-server weather-server
```

This scaffolds a project with the SDK wired up, a sample tool, and build scripts. Replace the sample with your API calls and you're running.

The [MCP docs](https://modelcontextprotocol.io/introduction) have quickstart guides for both TypeScript and Python. The Python SDK (`mcp`) follows the same patterns with async/await.
