pAInpoint.solutions
Intermediate40 min

Build a Remote MCP Server

Let AI assistants like Claude look things up in your own business systems, with read-only tools and the security basics in place from day one

Last reviewed

What You'll Learn

Concepts

  • • What MCP is: tools, resources, and prompts
  • • How hosts, clients, and servers fit together
  • • Local (stdio) versus remote (Streamable HTTP) servers
  • • The security model for a server on the internet

Hands-on

  • • A working server with two read-only tools
  • • Zod input and output schemas
  • • Testing with curl and the MCP Inspector
  • • Connecting it to Claude and Claude Code

What MCP Is#

The Model Context Protocol (MCP) is an open standard for connecting AI apps to outside systems. You write one MCP server for your order system, calendar, or inventory, and any AI app that supports MCP can use it. No custom integration per assistant. A server can offer three kinds of things:

Tools

The model decides when to call them

Functions the assistant can call, each with a name, a description, and an input schema. "Look up order A-10042" becomes a call to get_order_status.

Resources

The app or the user picks them

Read-only data the client can pull into context by URI, such as a price list, a policy document, or a product catalog.

Prompts

The user chooses them

Reusable message templates your server offers, often shown as slash commands, like "summarize this week's orders".

Most business use starts with tools. Three roles are involved in every connection:

Host

The AI app a person uses: Claude, Claude Code, ChatGPT, Cursor, and others.

Client

The connector inside the host. It keeps one connection to one server.

Server

Your program. It exposes tools, resources, and prompts over MCP. This guide builds one.

Local or Remote?#

Local (stdio)

The AI app starts your server as a program on the same computer and talks to it over standard input and output.

Good for:

  • • Nothing to host
  • • Can read local files
  • • Credentials come from environment variables

Trade-offs:

  • • Each person installs it themselves
  • • Only works on that one machine

Remote (Streamable HTTP)

Your server runs at an HTTPS address. Each message is an HTTP POST to one endpoint, and replies come back as JSON or a short event stream.

Good for:

  • • One deployment serves your whole team
  • • Works from web and mobile apps
  • • Central logging and access control

Trade-offs:

  • • Needs hosting and HTTPS
  • • Needs real authentication because it is on the internet

This guide builds a remote server, because that is what lets a whole team (or the Claude web and mobile apps) use it. The older HTTP+SSE transport is deprecated, so use Streamable HTTP for anything new.

Build the Server#

We use the official TypeScript SDK, version 2.4. Version 2 replaced the single @modelcontextprotocol/sdk package with smaller ones, so older tutorials will not match. You need Node.js 20 or newer.

1. Create the project

Terminal
mkdir acme-mcp && cd acme-mcp
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/server @modelcontextprotocol/express @modelcontextprotocol/node express zod

2. Write the server

Two tools, both read-only. Each has a Zod input schema, which the SDK turns into the JSON Schema the model sees and uses to reject bad arguments before your code runs. The order tool also declares an output schema, so clients get typed results.

server.js
// server.js: a minimal remote MCP server with two read-only tools.
// Node 20+, ES modules. Run: MCP_BEARER_TOKEN=... node server.js
import { timingSafeEqual } from 'node:crypto';

import { createMcpExpressApp, requireBearerAuth } from '@modelcontextprotocol/express';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHandler, McpServer, OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server';
import * as z from 'zod/v4';

const TOKEN = process.env.MCP_BEARER_TOKEN;
if (!TOKEN || TOKEN.length < 32) {
  console.error('Set MCP_BEARER_TOKEN to a random string of at least 32 characters.');
  process.exit(1);
}

// Stand-ins for your real systems. Swap these for a read-only database
// user or a read-only API key, never an admin credential.
const HOURS = {
  monday: '9:00 to 17:00', tuesday: '9:00 to 17:00', wednesday: '9:00 to 17:00',
  thursday: '9:00 to 17:00', friday: '9:00 to 16:00', saturday: '10:00 to 14:00',
  sunday: 'Closed',
};
const ORDERS = new Map([
  ['A-10042', { status: 'shipped', estimatedDelivery: '2026-11-12' }],
  ['A-10043', { status: 'processing', estimatedDelivery: '2026-11-15' }],
]);

function buildServer() {
  const server = new McpServer({ name: 'acme-store', version: '1.0.0' });

  server.registerTool(
    'get_business_hours',
    {
      title: 'Get business hours',
      description: 'Opening hours for one day of the week, or the whole week if no day is given.',
      inputSchema: z.object({
        day: z.enum(Object.keys(HOURS)).optional().describe('Lowercase day name, e.g. "monday"'),
      }),
      annotations: { readOnlyHint: true, openWorldHint: false },
    },
    async ({ day }) => {
      const result = day ? { [day]: HOURS[day] } : HOURS;
      return { content: [{ type: 'text', text: JSON.stringify(result) }] };
    },
  );

  server.registerTool(
    'get_order_status',
    {
      title: 'Get order status',
      description: 'Shipping status for one order. Returns status and estimated delivery date only.',
      inputSchema: z.object({
        orderId: z.string().regex(/^A-\d{5}$/).describe('Order number, e.g. "A-10042"'),
      }),
      outputSchema: z.object({
        orderId: z.string(),
        status: z.enum(['processing', 'shipped', 'delivered', 'not_found']),
        estimatedDelivery: z.string().nullable(),
      }),
      annotations: { readOnlyHint: true, openWorldHint: false },
    },
    async ({ orderId }) => {
      // Return only what the assistant needs. No names, addresses, or emails.
      const order = ORDERS.get(orderId);
      const output = order
        ? { orderId, ...order }
        : { orderId, status: 'not_found', estimatedDelivery: null };
      return {
        content: [{ type: 'text', text: JSON.stringify(output) }],
        structuredContent: output,
      };
    },
  );

  return server;
}

// Minimal shared-secret check for this example. For a production server that
// other people connect to, replace it with OAuth (see the security section).
const expected = Buffer.from(TOKEN);
const verifier = {
  async verifyAccessToken(token) {
    const given = Buffer.from(token);
    if (given.length !== expected.length || !timingSafeEqual(given, expected)) {
      throw new OAuthError(OAuthErrorCode.InvalidToken, 'Invalid token');
    }
    return {
      token,
      clientId: 'owner',
      scopes: [],
      expiresAt: Math.floor(Date.now() / 1000) + 3600,
    };
  },
};

// Local dev: binds 127.0.0.1 and rejects foreign Host and Origin headers.
// Behind a public URL, set HOST=0.0.0.0 and PUBLIC_HOSTNAME=mcp.example.com.
const host = process.env.HOST ?? '127.0.0.1';
const publicHostname = process.env.PUBLIC_HOSTNAME;
const app = createMcpExpressApp(
  publicHostname ? { host, allowedHosts: [publicHostname] } : { host },
);

const handler = toNodeHandler(createMcpHandler(buildServer));
app.all('/mcp', requireBearerAuth({ verifier }), (req, res) => {
  void handler(req, res, req.body);
});

const port = Number(process.env.PORT ?? 3000);
app.listen(port, host, () => {
  console.log(`MCP server listening on http://${host}:${port}/mcp`);
});

3. Run it

Generate a long random token and keep it in an environment variable. Never commit it or paste it into code.

Terminal
export MCP_BEARER_TOKEN="$(openssl rand -hex 32)"
node server.js
# MCP server listening on http://127.0.0.1:3000/mcp

Why a new server per request? createMcpHandler builds a fresh McpServer for every HTTP request. Nothing is kept in memory between calls, so you can run several copies behind a load balancer. Create database pools once, outside buildServer.

Test It#

Before you connect a real AI app, call the server directly. A plain curl request proves the endpoint and the token work:

Terminal
curl -s -X POST http://127.0.0.1:3000/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -H "Authorization: Bearer $MCP_BEARER_TOKEN" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_order_status","arguments":{"orderId":"A-10042"}}}'

# event: message
# data: {"result":{"content":[...],"structuredContent":{"orderId":"A-10042","status":"shipped","estimatedDelivery":"2026-11-12"}},"jsonrpc":"2.0","id":1}

The MCP Inspector is the official testing tool. The browser version lists your tools, shows their schemas, and lets you call them by hand: choose Streamable HTTP, enter http://127.0.0.1:3000/mcp, and add the Authorization header. The CLI version is useful for scripts. The current Inspector release needs a recent Node.js (22.23.4+, 24.22.1+, or 26.12.1+).

Terminal
# Visual tester in your browser
npx @modelcontextprotocol/inspector

# Or script it from the terminal (handy in CI)
npx @modelcontextprotocol/inspector --cli http://127.0.0.1:3000/mcp \
  --header "Authorization: Bearer $MCP_BEARER_TOKEN" \
  --method tools/call --tool-name get_order_status --tool-arg orderId=A-10043

Check these before moving on

  • A request with no token gets 401 and a WWW-Authenticate header
  • A request with a wrong Host or Origin header gets 403
  • tools/list shows both tools with their input schemas
  • A bad order number like "DROP TABLE" comes back as a validation error, not a crash
  • An unknown but well-formed order number returns not_found, not an exception

Connect an AI App#

AI apps that run in the cloud cannot reach 127.0.0.1. Deploy the server to a host with an HTTPS address first (see the deployment guide), and start it with HOST=0.0.0.0 and PUBLIC_HOSTNAME set to your domain.

Claude Code

Add it from the terminal, then run /mcp inside Claude Code to confirm it connected. This also works against your local server during development.

Terminal
claude mcp add --transport http acme-store https://mcp.example.com/mcp \
  --header "Authorization: Bearer YOUR_TOKEN"

Claude (web, desktop, mobile)

  • • Go to Customize, then Connectors, and choose Add custom connector.
  • • Enter your HTTPS URL, such as https://mcp.example.com/mcp. Claude connects from Anthropic's cloud, so it must be reachable from the internet.
  • • For the shared-token example, choose No sign-in and add an Authorization request header with the value Bearer YOUR_TOKEN. Request headers are a beta feature that not every account has yet.
  • • Without request headers, or for a server several people sign in to, use OAuth. Claude handles the sign-in flow when your server follows the MCP authorization spec.
  • • On Team and Enterprise plans, an Owner adds the connector for everyone.

Other AI apps

ChatGPT, Cursor, VS Code, and many other apps can connect to remote MCP servers. The steps and supported sign-in methods differ by app and plan, so check each app's own documentation. The server itself does not change.

Security Checklist#

An MCP server gives an AI model real access to your systems, and the model acts on whatever text reaches it. Design every tool as if a stranger could call it with any arguments, because a successful prompt injection makes that true.

Use real authorization in production

  • The shared token above suits a server only you (or one internal team) use. Anyone holding it has full access.
  • For a server other people sign in to, the MCP spec (2026-07-28) defines OAuth 2.1: your server is a resource server that checks tokens from an identity provider and publishes Protected Resource Metadata (RFC 9728).
  • The SDK covers the server half: swap the example verifier for one that checks your provider's tokens, set expectedResource so only tokens issued for this server pass, and serve the metadata with mcpAuthMetadataRouter.
  • Never accept or forward tokens meant for some other service. Tokens go in the Authorization header, never in the URL.

Lock down the network edge

  • Bind to 127.0.0.1 while developing. createMcpExpressApp does this and also rejects unexpected Host and Origin headers, which blocks DNS rebinding attacks from web pages.
  • When you bind to 0.0.0.0 for hosting, list your public hostname in allowedHosts.
  • Serve it over HTTPS only, behind your host's TLS.
  • Rate limit per token and per IP, at a gateway or with middleware such as express-rate-limit.

Least privilege, read-only first

  • Give the server its own read-only database user or a restricted API key, never an admin credential.
  • Ship read-only tools first. readOnlyHint and destructiveHint are hints for the client, not enforcement. Your credentials are the real limit.
  • When you add a write tool, require a human approval step in your own system, such as creating a draft a person confirms, rather than trusting the AI app's approval prompt alone.
  • Keep each tool narrow: "get order status" beats "run any SQL".

Return only what is needed

  • Everything a tool returns goes into the model's context, and often into the AI provider's conversation history.
  • Never return secrets, internal IDs you would not show a customer, or personal data the question did not need.
  • Validate every input with a tight Zod schema. The SDK rejects bad arguments before your handler runs.
  • Log the tool name, caller, duration, and outcome. Do not log arguments, results, or tokens.

Treat tool output as untrusted

  • Prompt injection: if a tool returns text a customer wrote (an order note, a review, an email), that text can contain instructions aimed at the model.
  • Prefer structured fields over free text, and label any user-written text clearly as data.
  • The risky mix is private data plus untrusted text plus a way to send data out. Avoid giving one session all three.
  • Watch for tools whose descriptions change unexpectedly, in your own server and in third-party ones you connect.

Next Steps

Once your read-only tools work, put the server behind monitoring and alerts before you add anything that writes.