To deploy a remote MCP server, serve it over Streamable HTTP from a process that stays up, put a token check in front of the endpoint and hand its URL to your MCP clients. On Modelence the server is one service in modelence.config.json, deployed with one command. Modelence builds it on an official Node.js image, runs it as containers on AWS in the region you pick out of 17 and serves it over HTTPS, so Claude Code, Cursor or your own agent can connect from anywhere.
This guide builds a small Model Context Protocol server with version 2 of the official TypeScript SDK, which implements the 2026-07-28 revision of the spec. Its two tools look up packages on npm, so a coding agent can check a library's latest version and compare how widely alternatives are used. You'll protect it with a bearer token, cache lookups in Redis, deploy it and connect it to Claude Code and Cursor. The steps carry over to any server built on the SDK, whatever its tools call. If you already have a server, skip to Describe the server in modelence.config.json.
MCP server on Modelence at a glance
- Transport
- Streamable HTTP on one /mcp route, the remote transport Claude Code, Cursor and other MCP clients connect to
- Start command
- node server.js after npm ci, on the official node-22-slim image, with no Dockerfile to write
- State
- A fresh McpServer per request, so any container answers any call and more containers mean more capacity
- Long streams
- The SDK writes an SSE keep-alive every 15 seconds, well inside the load balancer's 300-second idle timeout
- Auth
- A bearer token kept as a secret and checked by the SDK's requireBearerAuth, or OAuth tokens from your identity provider
- Regions
- 17 AWS regions, with the server and its Redis, PostgreSQL or MongoDB in the one you pick
- Price
- Free plan to start, and paid plans from $20 a month with the $20 included as usage
Before you start
- Node.js 20 or newer, which the MCP TypeScript SDK needs, and npm
- A Modelence account, which you can create for free
- Claude Code, Cursor or another MCP client that supports remote servers, to connect at the end
Create the MCP server
Start a project and install the SDK's server package, its Node.js and Express adapters, Express itself and Zod, which describes the input of each tool:
mkdir npm-tools && cd npm-tools
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/server @modelcontextprotocol/node @modelcontextprotocol/express express zod
Then add server.js. Most of it is the two tools, and the rest decides how the server behaves once it's on the internet:
createMcpHandler(buildServer)builds a newMcpServerfor every HTTP request and holds nothing in between. That is the request model of the 2026-07-28 spec, and clients still on a 2025 revision, which open withinitialize, are served the same way.requireBearerAuthruns before the/mcproute and answers any request that lacks the token fromMCP_TOKENwith a 401 and aWWW-Authenticateheader.timingSafeEqualcompares the token without leaking its length through timing./healthis registered outside the token check, so the platform's health check gets its 200.createMcpExpressAppreturns an Express app that already parses JSON bodies. Withhost: '0.0.0.0'it accepts anyHostheader, and the SDK logs a warning at startup that suggestsallowedHostsor authentication. The bearer token is that authentication.- Both tools set
readOnlyHint, which tells clients they change nothing. A package that doesn't exist comes back as a result withisError, so the model reads the reason instead of getting a protocol error.
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';
async function getJson(url) {
const response = await fetch(url, { signal: AbortSignal.timeout(10_000) });
if (response.status === 404) return null;
if (!response.ok) throw new Error(`${url} answered ${response.status}`);
return response.json();
}
function asText(value) {
return { content: [{ type: 'text', text: JSON.stringify(value, null, 2) }] };
}
// Runs once per request: every call gets a fresh server, so nothing is kept in the process.
function buildServer() {
const server = new McpServer({ name: 'npm-tools', version: '1.0.0' });
server.registerTool(
'package_info',
{
description: 'Latest version, description, license and supported Node.js versions of an npm package',
inputSchema: z.object({ name: z.string().min(1).max(214) }),
annotations: { readOnlyHint: true },
},
async ({ name }) => {
const pkg = await getJson(`https://registry.npmjs.org/${name.replace('/', '%2F')}/latest`);
if (!pkg) {
return { ...asText({ error: `No package named ${name}` }), isError: true };
}
return asText({
name: pkg.name,
version: pkg.version,
description: pkg.description,
license: pkg.license,
node: pkg.engines?.node ?? 'any',
});
},
);
server.registerTool(
'weekly_downloads',
{
description: 'Downloads in the last 7 days for up to 10 npm packages, to compare how widely they are used',
inputSchema: z.object({ names: z.array(z.string().min(1)).min(1).max(10) }),
annotations: { readOnlyHint: true },
},
async ({ names }) => {
const counts = await Promise.all(
names.map(async (name) => {
const data = await getJson(`https://api.npmjs.org/downloads/point/last-week/${name}`);
return { name, downloads: data?.downloads ?? null };
}),
);
return asText(counts);
},
);
return server;
}
const handler = createMcpHandler(buildServer);
const mcp = toNodeHandler(handler);
// Lets in requests that send MCP_TOKEN as a bearer token.
const auth = requireBearerAuth({
verifier: {
async verifyAccessToken(token) {
const expected = Buffer.from(process.env.MCP_TOKEN ?? '');
const given = Buffer.from(token);
if (expected.length === 0 || given.length !== expected.length || !timingSafeEqual(given, expected)) {
throw new OAuthError(OAuthErrorCode.InvalidToken, 'Invalid token');
}
return { token, clientId: 'team', scopes: [], expiresAt: Math.floor(Date.now() / 1000) + 3600 };
},
},
});
const app = createMcpExpressApp({ host: '0.0.0.0' });
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
app.all('/mcp', auth, (req, res) => {
void mcp(req, res, req.body);
});
const port = Number(process.env.PORT) || 3000;
app.listen(port, '0.0.0.0', (error) => {
if (error) {
throw error;
}
console.log(`MCP server listening on port ${port}`);
});Run it and call a tool
Add a start script for production and a dev script that restarts the server on every change:
"scripts": {
"dev": "node --watch server.js",
"start": "node server.js"
}
Start it with a token of your choosing, then call a tool through the MCP Inspector's command-line mode from a second terminal. It speaks the protocol the way an agent would, which a plain curl can't do for you:
MCP_TOKEN=dev-token npm run dev
# in a second terminal
npx @modelcontextprotocol/inspector --cli http://localhost:3000/mcp \
--transport http --header "Authorization: Bearer dev-token" \
--method tools/call --tool-name package_info --tool-arg name=express
The answer carries Express's latest version, license and engines field. Swap --method tools/call and the tool flags for --method tools/list to see both tools with their input schemas. To try it from Claude Code before deploying, add the local URL with the same header, as in Connect Claude Code and Cursor.
A Modelence local environment can also run the server on your machine with the environment's variables, including MCP_TOKEN and the Redis connection string from the next section, so nothing has to live in a .env file. Connect the project once with npx modelence@latest setup, which signs you in through the browser and lets you pick or create an app and environment, then run npx modelence@latest dev in place of npm run dev.
npx modelence@latest setup
npx modelence@latest devAdd a database
- MongoDB
MONGODB_URI - Postgres
DATABASE_URL - Redis
REDIS_URL
Because every request gets a fresh server object, anything that has to last longer than one call, such as a cache, a user's preferences or the state of a multi-step task, belongs in a database that every container shares. Modelence runs managed Redis, PostgreSQL and MongoDB in the app's region, reached through connection strings in environment variables, with backups of production databases.
For this server, Redis is a good fit: npm lookups repeat a lot, and a short cache spares the registry and speeds up the agent. Install the client with npm install redis, create it once at the top of server.js and wrap the registry call. REDIS_URL comes from the cache resource you declare in the next section.
Per-user state works the same way. A tool handler receives the verified token's details as ctx.http.authInfo, so a key such as prefs:${ctx.http.authInfo.clientId} keeps each caller's data apart. With PostgreSQL, through pg, Prisma or Drizzle, or with MongoDB through its driver, create the client once per process in the same place, outside buildServer, so requests share its connections.
import { createClient } from 'redis';
// One Redis client per process, shared by every request.
const redis = createClient({ url: process.env.REDIS_URL });
redis.on('error', (error) => console.error('Redis error', error));
await redis.connect();
async function cached(key, seconds, load) {
const hit = await redis.get(key);
if (hit) return JSON.parse(hit);
const value = await load();
if (value) await redis.set(key, JSON.stringify(value), { EX: seconds });
return value;
}
// In package_info, instead of calling getJson directly:
const pkg = await cached(`package:${name}`, 600, () =>
getJson(`https://registry.npmjs.org/${name.replace('/', '%2F')}/latest`),
);Describe the server in modelence.config.json
Modelence runs the server as a Node.js service: it installs dependencies with npm ci on an official Node.js image and keeps node server.js running. The file below also points the health check at /health, creates the Redis cache and declares MCP_TOKEN as a secret, so its value never goes into the repository. Put it at the root of the project and commit it:
{
"$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1",
"resources": {
"mcp": {
"type": "service",
"image": "node-22-slim",
"build": { "commands": ["npm ci"] },
"start": { "commands": ["node server.js"] },
"healthCheck": { "type": "http", "path": "/health" }
},
"cache": { "type": "redis" }
},
"env": {
"MCP_TOKEN": { "type": "secret" },
"REDIS_URL": { "type": "resource", "resource": "cache", "output": "url" }
}
}Adjust the config for your project
- For a server written in TypeScript, compile it in the build and start the output:
"build": { "commands": ["npm ci", "npm run build"] }and"start": { "commands": ["node dist/server.js"] }. - The SDK needs Node.js 20 or newer.
node-22-slimis the default image, andnode-24-slimor an Alpine image such asnode-22-alpineworks too. - With pnpm, install with
corepack enable && pnpm install --frozen-lockfile. - A Python server built with the official Python SDK or FastMCP runs from its own Dockerfile. Set
"dockerfile": "Dockerfile"and"ports": [8000]on the service, have the server listen on0.0.0.0and run it in stateless mode, which FastMCP turns on withstateless_http=True. Dockerfile services covers the rest. - Leave out the
cacheresource andREDIS_URLif the server has no state to share. - Secrets such as
MCP_TOKENand the API keys your tools call are declared with"type": "secret"and no value. The deploy asks for each one in the browser, and the dashboard shows them later under Environment variables, logging every view.
Check the build locally
Run the build and start commands in the order Modelence runs them, then check the health route and list the tools with a raw request from a second terminal. A deploy runs the same commands, so a failure here would fail there too.
npm ci && MCP_TOKEN=dev-token PORT=3000 node server.js
# in a second terminal
curl http://localhost:3000/health
curl -X POST http://localhost:3000/mcp \
-H "Authorization: Bearer dev-token" \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'Deploy
Generate a long random token for production first, for example with openssl rand -hex 32, and keep it at hand. Then deploy from the project directory:
npx modelence@latest deploy
The command signs you in through the browser, where you choose the organization, app and environment or create new ones, and asks for the variables the environment doesn't have yet. Paste the token as MCP_TOKEN there. It then uploads the project and streams the build until the server is live. The first deploy of an environment also asks for its AWS region, which is where the containers and the Redis cache are created. For later deploys, --app <app> --env <env> picks the target up front.
The server answers at https://<app>-<environment>.cloud.modelence.app/mcp, and the environment's Logs page shows MCP server listening on port 3000. For a domain of your own, such as mcp.example.com, add it under Domains in the dashboard. Every app has a sandbox and a production environment, each with its own token and cache, deployed from the same file.
Let your coding agent deploy it
In Claude Code, Cursor or Codex, open the project and paste Deploy using https://modelence.com/skill.md. The agent reads the docs, writes modelence.config.json, runs the build to check it and deploys, pausing whenever a step needs you to sign in or enter a secret.
Connect Claude Code and Cursor
In Claude Code, add the server with the HTTP transport and the token as a header:
claude mcp add --transport http npm-tools https://<app>-<environment>.cloud.modelence.app/mcp \
--header "Authorization: Bearer <token>"
Run /mcp in a Claude Code session to see it connected with its two tools. That command stores the server for you alone in this project. To share it with your team through the repository, add --scope project, which writes .mcp.json at the project root, and replace the token with ${NPM_TOOLS_TOKEN}, which Claude Code fills in from each person's environment.
In Cursor, put the server in .cursor/mcp.json for one project or ~/.cursor/mcp.json for all of them. Cursor reads ${env:NAME} from the environment in url and headers:
{
"mcpServers": {
"npm-tools": {
"url": "https://<app>-<environment>.cloud.modelence.app/mcp",
"headers": { "Authorization": "Bearer ${env:NPM_TOOLS_TOKEN}" }
}
}
}
Other clients that support remote servers take the same two things, the URL and the header.
Production readiness
Keep the server stateless
Modelence spreads requests across a service's containers with no session affinity, which suits a stateless MCP server: any container can answer any call, so you add capacity by raising the container count under Configure, and two or more containers keep the server up through a crash. createMcpHandler works this way already, since the 2026-07-28 spec has no Mcp-Session-Id and the SDK answers clients on 2025 revisions one request at a time too.
Keep it that way by giving the factory nothing but tool definitions. Connection pools and clients go at module scope, and anything a later call needs goes in Redis or PostgreSQL, keyed by the caller or by an id the tool returns to the model. An older server built on the 2025 session transport, with sessionIdGenerator set, keeps its sessions in process memory. Run that one on a single container, or move it to createMcpHandler, which the SDK's upgrade guide covers.
Keep long streams alive
The load balancer closes a connection that carries nothing for 300 seconds. The SDK writes an SSE comment, : keepalive, every 15 seconds on each stream it holds open, so streams stay up as long as you leave keepAliveMs at its default.
By default the handler answers a call with a single response and switches to a stream only when a tool sends progress or log notifications. A tool that runs for minutes without sending anything would sit silent on the connection, so either have it report progress, or make every response a stream, which brings the keep-alives with it:
const handler = createMcpHandler(buildServer, { responseMode: 'sse' });
Choose how clients authenticate
One shared token in MCP_TOKEN suits a server your team or your own agents use. Rotate it by changing the secret under Environment variables and redeploying, then updating each client's header.
When every person should sign in with their own account, make the server an OAuth resource server. Keep requireBearerAuth, but have verifyAccessToken check JWTs from your identity provider, such as Auth0, Clerk or WorkOS, and fill in clientId, scopes and expiresAt from the token's claims. Add mcpAuthMetadataRouter to publish the protected resource metadata, so clients like Claude Code find the sign-in page from the 401 on their own. The SDK's authorization guide has both pieces. A token without expiresAt is always rejected, which is why the static verifier in server.js sets one.
Let tool calls finish during a deploy
When a container stops, it gets SIGTERM, and requests can keep arriving for about 10 seconds after it. Keep serving for that long, then stop accepting connections and exit once open requests are done. Capture the server that app.listen returns and add:
const httpServer = app.listen(port, '0.0.0.0');
process.on('SIGTERM', () => {
setTimeout(() => httpServer.close(() => process.exit(0)), 10_000);
});
Modelence waits 30 seconds between SIGTERM and SIGKILL by default. If some tools run longer, raise it with "stopTimeout": 120 on the service, the maximum.
Log tool calls
Whatever the server prints shows on the environment's Logs page with no setup, so a line per tool call, such as console.log('package_info', name), tells you which tools agents use and which ones fail. Leave tokens and full arguments out of those lines if they can hold personal data. For traces and metrics, add a telemetry resource and start the server with the OpenTelemetry Node.js auto-instrumentation, as Deploy setup shows, and every request and outgoing fetch is traced.
Modelence vs Vercel, Cloudflare and AWS AgentCore for MCP servers
"Deploy an MCP server" searches mostly lead to Vercel, Cloudflare Workers and Amazon Bedrock AgentCore Runtime. All three host the stateless Streamable HTTP servers this guide builds, each in its own way. Each figure below is taken from the platform's own docs or pricing page, as checked in November 2026.
| Platform | How an MCP server runs | Good to know | Pricing |
|---|---|---|---|
| Modelence | node server.js as long-running containers on AWS in 17 regions, with managed Redis, PostgreSQL and MongoDB next to it | Tools can run for minutes, and the SDK's keep-alives hold long streams open | Free plan, then from $20 a month with $20 of usage included |
| Vercel | mcp-handler on Vercel Functions with Fluid compute | 300 seconds per request on Hobby, up to 800 on Pro | Hobby is free for personal, non-commercial use; Pro is $20 a month with one seat and $20 of usage credit |
| Cloudflare Workers | createMcpHandler from the Agents SDK, stateless, with state in Durable Objects, D1 or KV | 100,000 requests a day on the Free plan | Free, or Workers Paid from $5 a month |
| AWS AgentCore Runtime | An ARM64 container serving stateless Streamable HTTP at /mcp on port 8000 | Sessions end after 15 idle minutes and last at most 8 hours | Per second, from $0.0895 per vCPU-hour and $0.00945 per GB-hour, with no CPU charge during I/O wait |
Vercel is the natural home for an MCP server that sits next to a Next.js app already deployed there, as long as each tool finishes within the function duration. Cloudflare Workers suit a light, high-volume server close to users, with Cloudflare's storage for state. AgentCore Runtime fits teams building agents on Amazon Bedrock that want MCP servers under the same IAM roles and billing. Modelence fits a server that is a regular Node.js process, or any language from a Dockerfile, with tools that query its own database or run for minutes, in the AWS region you choose and without setting up AWS yourself. For more on Vercel, see Modelence vs Vercel.
Next steps
Frequently asked questions
How do I deploy an MCP server?
Serve it over Streamable HTTP instead of stdio, make it listen on the PORT variable on all interfaces, require a token on the MCP route and run it on a platform that keeps the process up behind HTTPS. On Modelence you put the build and start commands in modelence.config.json and run npx modelence@latest deploy, and the server gets a URL such as https://<app>-<environment>.cloud.modelence.app/mcp that any MCP client can use.
What is the difference between a local and a remote MCP server?
A local MCP server runs on your machine as a child process of the client, which talks to it over stdio, so only you can use it and it stops when the client does. A remote server runs on a host and speaks Streamable HTTP, so a whole team, a CI job or an agent running in the cloud can use the same server, and it can reach databases and internal APIs that laptops shouldn't hold keys for. The same McpServer code can serve both, since the TypeScript SDK has a stdio entry point and an HTTP handler.
Should a remote MCP server be stateless?
Yes, in most cases. The 2026-07-28 revision of the spec drops sessions, and version 2 of the TypeScript SDK builds a fresh server for every request with createMcpHandler, so any container can answer any call and scaling means adding containers. Data that must outlive a request goes in Redis or PostgreSQL, keyed by the caller. A server that still uses the 2025 session transport keeps sessions in memory and should run on a single container.
How do I add a remote MCP server to Claude Code?
Run claude mcp add --transport http <name> <url> --header "Authorization: Bearer <token>", then check it with /mcp inside a Claude Code session. The server is saved for you in the current project by default. With --scope project it goes into .mcp.json at the project root, where ${VAR} placeholders let each teammate supply their own token from the environment.
How do I add a remote MCP server to Cursor?
Add an entry under mcpServers in .cursor/mcp.json for one project, or in ~/.cursor/mcp.json for every project, with the server's url and a headers object holding the Authorization header. Write the token as ${env:NAME} so Cursor reads it from your environment instead of the file.
Can I host an MCP server on AWS?
Yes. Modelence runs the server on AWS in the region you choose and manages the containers, HTTPS and databases, so there is no AWS account setup on your side. On AWS directly, Amazon Bedrock AgentCore Runtime hosts MCP servers as ARM64 containers serving /mcp on port 8000, and AWS Labs publishes a project for running stdio MCP servers inside Lambda functions.
Can I host an MCP server on Vercel?
Yes, Vercel documents MCP servers built with its mcp-handler package, which run on Vercel Functions with Fluid compute. Each request is limited to the function duration, 300 seconds on Hobby and up to 800 seconds on Pro. A server whose tools run longer, or that should run as one long-lived process next to its database, fits a platform that runs containers, such as Modelence.
Can I host an MCP server for free?
You can start on Modelence's free plan, which is enough to try a server with your own agent. Paid plans start at $20 a month with the same $20 included as cloud usage, cover the whole team with no per-seat charge and add managed Redis and PostgreSQL for the server's state.
Can I deploy an MCP server written in Python?
Yes. A server built with the official Python SDK or FastMCP runs on Modelence from its own Dockerfile: set dockerfile and ports, such as [8000], on the service, listen on 0.0.0.0 and use the streamable HTTP transport in stateless mode. Health checks, secrets, databases and the client setup are the same as in this guide.