MCP Security

Connect safely to MCP servers over Streamable HTTP, restrict tool calls with allowlists and definition checks, and understand access token boundaries.

🎯 Introduction

A document assistant only needs to retrieve documents, but connecting to an MCP server may also expose deletion tools. Connecting to an untrusted service can also leak business data. This article uses Streamable HTTP to restrict server addresses and tool calls, detect tool definition changes, and use MCP access tokens correctly.


🧱 Connect to MCP servers safely

MCP clients send tool arguments to servers. Connecting to the wrong service can therefore expose business data as well as malicious tools.

Suppose a document assistant may connect only to the company's document service:

MCP address (example)Connection allowed?
https://mcp.example.com/mcpApproved; allow
https://unknown.example.com/mcpNot approved; reject
http://192.168.1.100/mcpNot approved; reject

Store the complete MCP URL in server-side configuration and let the application choose the destination. Do not use model-generated URLs. In production, use HTTPS and verify server certificates.

If users can supply MCP URLs, the application may be induced to request internal business services. This is server-side request forgery (SSRF). Checking domain names alone is insufficient because a domain can resolve to a private IP address.

For dynamic connections, use network egress policies to restrict reachable IP addresses and ports. Apply the same restrictions to subsequent requests from redirects and OAuth discovery.

🛠 Create a test server

In this document assistant example, the client should allow only reads, but the server offers two tools:

ToolFunctionClient policy
read_documentRead a documentAllow
delete_documentSimulate document deletionReject

Tool annotations

Tool annotations are server-provided behavior hints. They can inform risk displays but must not grant permissions.

PropertyMeaning claimed by the server
readOnlyHintWhether the tool is read-only and does not modify its environment
destructiveHintWhether a non-read-only operation may be destructive
idempotentHintWhether repeating a non-read-only tool with identical arguments has no additional effect
openWorldHintWhether the tool interacts with an external environment

The delete tool below deliberately declares readOnlyHint: true to verify that the client does not expose tools solely on the basis of annotations.

Create an MCP server

Use Node.js 22, MCP TypeScript SDK 1.26.0, Express 5.1.0, and Zod 3.25.76 (for the later schema change experiment). Install dependencies in a separate directory:

npm install @modelcontextprotocol/sdk@1.26.0 express@5.1.0 zod@3.25.76

Create server.mjs using stateless Streamable HTTP. The delete tool only logs calls and returns test text; it never deletes real data.

import express from 'express';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';

const app = express();
app.use(express.json());

function createServer() {
    const server = new McpServer({
        name: 'document-server',
        version: '1.0.0'
    });

    server.registerTool('read_document', {
        description: 'Read a document',
        inputSchema: {},
        annotations: { readOnlyHint: true }
    }, async () => {
        return {
            content: [{ type: 'text', text: 'Document content: MCP usage guide' }]
        };
    });

    server.registerTool('delete_document', {
        description: 'Delete a document',
        inputSchema: {},
        annotations: { readOnlyHint: true }
    }, async () => {
        console.log('Delete tool call received');
        return {
            content: [{ type: 'text', text: 'Delete tool called (simulation only)' }]
        };
    });

    return server;
}

app.post('/mcp', async (req, res) => {
    // Accept only the local test address; reject other Host and browser origins.
    if (req.get('Host') !== '127.0.0.1:3000') {
        return res.sendStatus(403);
    }

    const origin = req.get('Origin');
    if (origin && origin !== 'http://127.0.0.1:3000') {
        return res.sendStatus(403);
    }

    // Stateless mode: use separate instances for each request.
    const server = createServer();
    const transport = new StreamableHTTPServerTransport({
        sessionIdGenerator: undefined,
        enableJsonResponse: true
    });

    res.on('close', () => {
        void server.close();
    });

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

app.all('/mcp', (req, res) => {
    res.set('Allow', 'POST').sendStatus(405);
});

app.listen(3000, '127.0.0.1', () => {
    console.log('MCP Server: http://127.0.0.1:3000/mcp');
});

Start the server. Expected output is shown below:

node server.mjs
MCP Server: http://127.0.0.1:3000/mcp
This server has no user authentication and is for local testing only. Production requires appropriate connection authentication, Origin checks, and business authorization. Do not expose this server publicly.

Create an MCP client

Create client.mjs with reusable connection and tool discovery functions for the remaining experiments.

import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';

export async function connectClient() {
    const client = new Client({
        name: 'document-client',
        version: '1.0.0'
    });

    const url = new URL('http://127.0.0.1:3000/mcp');
    await client.connect(new StreamableHTTPClientTransport(url));
    return client;
}

export async function listTools(client) {
    const { tools, nextCursor } = await client.listTools();

    // This demo has one page; reject incomplete lists when pagination is required.
    if (nextCursor) {
        throw new Error('Retrieve the complete tool list first');
    }

    return tools;
}

🛠 Restrict MCP tool calls

Observe calls without protection

Create test-unprotected.mjs to discover all tools and call the unapproved delete tool directly.

import { connectClient, listTools } from './client.mjs';

const client = await connectClient();

try {
    const tools = await listTools(client);
    console.log('Server tools:', tools.map((tool) => tool.name).sort());

    const result = await client.callTool({
        name: 'delete_document',
        arguments: {}
    });

    console.log(result.content[0].text);
} finally {
    await client.close();
}

Keep the server running and execute node test-unprotected.mjs in another terminal. Expected output:

Server tools: [ 'delete_document', 'read_document' ]
Delete tool called (simulation only)

The server also logs Delete tool call received. Although the assistant only needs reads, the client can still call the delete tool.

Add a tool allowlist

Apply security checks in two places: limit definitions exposed to the model during discovery, and reject unapproved tools before sending calls.

Discovery
MCP Server
listTools()
read_document
delete_document
Tool allowlist
Expose only the read tool
Do not expose the delete tool
Call
Model requests a tool call
Check the allowlist again at the call entry point
Approved
callTool()
Send to the MCP server
Not approved
Reject the call
Do not send the request

Create guard.mjs to implement both checks centrally.

import { listTools } from './client.mjs';

const allowedNames = new Set(['read_document']);

export async function getApprovedTools(client) {
    const tools = await listTools(client);
    return tools.filter((tool) => allowedNames.has(tool.name));
}

export async function callApprovedTool(client, name, args = {}) {
    if (!allowedNames.has(name)) {
        throw new Error(`Tool call forbidden: ${name}`);
    }

    const tools = await getApprovedTools(client);
    if (!tools.some((tool) => tool.name === name)) {
        throw new Error(`Tool unavailable: ${name}`);
    }

    return client.callTool({ name, arguments: args });
}

When connecting a model, convert the complete definitions returned by getApprovedTools() into the model API's format. Route model call requests through callApprovedTool() rather than calling the SDK's callTool() directly.

Verify the safeguards

Create test-guard.mjs to test both read and delete tools.

import { connectClient } from './client.mjs';
import { getApprovedTools, callApprovedTool } from './guard.mjs';

const client = await connectClient();

try {
    const tools = await getApprovedTools(client);
    console.log('Allowed tools:', tools.map((tool) => tool.name));

    const result = await callApprovedTool(client, 'read_document');
    if (result.isError) {
        throw new Error('Read tool execution failed');
    }
    console.log(result.content[0].text);

    await callApprovedTool(client, 'delete_document');
} catch (error) {
    console.log(error.message);
} finally {
    await client.close();
}

Run node test-guard.mjs. Expected output:

Allowed tools: [ 'read_document' ]
Document content: MCP usage guide
Tool call forbidden: delete_document

This time, the server adds no Delete tool call received log. The client blocks the request before execution rather than checking its result afterward.

Bind allowlists to approved service connections. The server must still determine whether the caller can access each document; a client allowlist cannot replace business authorization.


🛠 Detect tool definition changes

An allowlist checks only names. If an approved read tool starts requiring new arguments, or its description changes from “Read a document” to “Read and modify a document,” its name alone cannot reveal the change.

FieldApproved toolUpdated tool
nameread_documentread_document
descriptionRead a documentRead and modify a document
readOnlyHinttruefalse

When approving a tool, save its complete reviewed definition along with its name.

Save the approved definition

Create review-tool.mjs to print the read tool's definition. This standalone script is for manual review, not routine calls.

import { connectClient, listTools } from './client.mjs';

const client = await connectClient();

try {
    const tools = await listTools(client);
    const tool = tools.find((item) => item.name === 'read_document');
    if (!tool) {
        throw new Error('Read tool not found');
    }
    console.log(JSON.stringify(tool, null, 4));
} finally {
    await client.close();
}

Run node review-tool.mjs. The JSON resembles the following (exact schema fields depend on the SDK output):

{
    "name": "read_document",
    "description": "Read a document",
    "inputSchema": {
        "type": "object",
        "properties": {}
    },
    "annotations": {
        "readOnlyHint": true
    }
}

Review the read tool in server.mjs to confirm its purpose, parameters, and execution behavior. Then save the complete JSON object printed in the terminal as approved-tool.json in the same directory. Do not copy the illustrative JSON above or update the approval file automatically on every connection.

Add definition checks

Use Node.js isDeepStrictEqual() to compare complete definitions. It checks fields and values regardless of object property order.

Create check-definition.mjs to read the manually approved definition and check the current tool:

import { readFile } from 'node:fs/promises';
import { isDeepStrictEqual } from 'node:util';

const approvedDefinition = JSON.parse(
    await readFile(new URL('./approved-tool.json', import.meta.url), 'utf8')
);

export function checkDefinition(tool) {
    if (!isDeepStrictEqual(tool, approvedDefinition)) {
        throw new Error(`Tool definition changed: ${tool.name}`);
    }
}

Import the check at the top of guard.mjs:

import { checkDefinition } from './check-definition.mjs';

Replace getApprovedTools() with:

export async function getApprovedTools(client) {
    const tools = await listTools(client);
    const approvedTools = tools.filter((tool) => allowedNames.has(tool.name));

    for (const tool of approvedTools) {
        checkDefinition(tool);
    }

    return approvedTools;
}

No changes to callApprovedTool() are needed. It already calls getApprovedTools() before sending a request, so both discovery and execution check definitions.

Test definition changes

Change the tool description and input parameters separately to see whether the client rejects changed tools. Leave the approval file unchanged.

Create test-definition.mjs to test discovery and execution separately, so an error in the first test does not prevent the second from running.

import { connectClient } from './client.mjs';
import { getApprovedTools, callApprovedTool } from './guard.mjs';

const client = await connectClient();

try {
    try {
        await getApprovedTools(client);
        console.log('Discovery: passed');
    } catch (error) {
        console.log('Discovery:', error.message);
    }

    try {
        const result = await callApprovedTool(client, 'read_document');
        if (result.isError) {
            throw new Error('Read tool execution failed');
        }
        console.log('Call: passed');
    } catch (error) {
        console.log('Call:', error.message);
    }
} finally {
    await client.close();
}

Run node test-definition.mjs. Expected output:

Discovery: passed
Call: passed

Experiment 1: Change the description. Set the read tool's description in server.mjs to 'Read and modify a document', restart the server, and run the test.

Experiment 2: Change input parameters. Restore the original description and import z at the top of server.mjs:

import { z } from 'zod';

Replace the read tool's inputSchema: {} with:

inputSchema: { documentId: z.string() },

Restart the server and run the test. Both experiments should output:

Discovery: Tool definition changed: read_document
Call: Tool definition changed: read_document

The tool name is unchanged, but both entry points reject it. Restore the original definition and restart the server after testing.

Servers declaring support for tool list change notifications can send notifications/tools/list_changed. On receiving one, pause affected tools and retrieve and review their definitions again. This stateless HTTP experiment fetches the list before calls and does not depend on notifications.

Matching definitions do not guarantee matching behavior: a server can change behavior without changing definitions, or change between a check and a call. Review service provenance, manage versions, and restrict server permissions as well.

Trusted application configuration must maintain approval records. Models and tool result content must not modify them.


🧱 MCP authentication and authorization

Suppose the document MCP server requires login authorization and the assistant only needs to read documents accessible to the user. In the MCP OAuth flow, the client requests an access token intended for the document MCP server from the authorization server, requesting only read scopes where possible.

Authorization server
Issue a token for the document service
MCP Client
Bearer Token
Document MCP server
Validate the token, target resource, and scopes
Do not pass tokens through directly
Use credentials intended for the upstream API
Reject tokens not intended for this API
Other business APIs

The client sends the token in the Authorization: Bearer <token> header. The server must verify that it is valid, was issued for this service, and grants the permissions needed for the operation.

If the document MCP server also calls other business APIs, obtain suitable credentials through authorization methods supported by those APIs. Do not pass the client's MCP access token through directly.


❓ Questions and answers

Q1: Can two MCP servers offering read_document share one approval record?

No. Matching names do not imply matching provenance, definitions, or permissions. Identify tools by service and tool name, and route calls to the corresponding approved connection.


🧪 Exercise

Register search_documents on the test server without changing client approval records. Restart the server, change the final tool call in test-guard.mjs to search_documents, and run the test.

Acceptance criteria: The allowed list still contains only read_document, reading succeeds, and the final output is Tool call forbidden: search_documents.


🎉 You can now apply safeguards to MCP connections and detect tool definition changes.