DEV Community

Manoj Kumar
Manoj Kumar

Posted on

How I test a remote MCP server before shipping it

A local stdio MCP server is easy to test. You run it, call a tool, and see if the output looks right.

A remote one is different. It sits on a public URL, has an OAuth server in front of it, and gets called by Claude, ChatGPT, Cursor and whatever script someone writes at 2am. Most of the ways it breaks have nothing to do with your tools. The client never starts sign-in. A token for the wrong server gets accepted. A missing scope comes back as a 500 instead of a challenge.

While building my remote MCP template I ended up with 85 tests (58 in TypeScript, 27 in Python). Here's what they check and why, so you can copy the approach even if you never use my code.

Rule 1: test through a real MCP client, not your handlers

The biggest mistake I made early on was calling tool functions directly. Those tests passed while real clients failed, because the bug was in transport, headers or auth.

Now every test goes through the official SDK client, using the app's own fetch so nothing needs a port:

/** fetch bound to the in-process app, so tests exercise the real HTTP surface. */
export function appFetch(app: App): typeof fetch {
  return (async (input, init) => app.fetch(new Request(input, init))) as typeof fetch;
}

export async function connectClient(app: App, accessToken?: string) {
  const client = new Client({ name: 'kit-test', version: '1.0.0' });
  const transport = new StreamableHTTPClientTransport(new URL('/mcp', BASE), {
    fetch: appFetch(app),
    requestInit: accessToken ? { headers: { authorization: `Bearer ${accessToken}` } } : undefined
  });
  await client.connect(transport);
  return client;
}
Enter fullscreen mode Exit fullscreen mode

It's fast (the whole TS suite runs in about 3 seconds) and it tests the same path Claude takes.

Rule 2: the 401 is a feature, so test it like one

When a client hits /mcp without a token, the server has to answer 401 with a WWW-Authenticate header that points at the protected resource metadata. If that header is missing or wrong, clients just say "couldn't connect" and never start the OAuth flow.

So the first test in the suite is literally "what Claude does first":

it('answers an unauthenticated /mcp call with 401 and a resource_metadata challenge', async () => {
  const res = await app.fetch(new Request(`${BASE}/mcp`, {
    method: 'POST',
    headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
    body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} })
  }));
  expect(res.status).toBe(401);
  const challenge = res.headers.get('www-authenticate') ?? '';
  expect(challenge).toMatch(/^Bearer /);
  expect(challenge).toContain(`resource_metadata="${BASE}/.well-known/oauth-protected-resource/mcp"`);
});
Enter fullscreen mode Exit fullscreen mode

I follow that with checks on the metadata docs themselves: the resource matches the MCP URL, the auth server advertises S256 only, and the registration endpoint is where it says it is.

Rule 3: write the "should fail" tests first

Happy-path OAuth is maybe 20% of the auth tests. The rest prove that bad things get rejected:

  • garbage tokens, expired tokens and tokens issued for a different deployment all get 401
  • a wrong PKCE verifier returns invalid_grant and burns the code, so a replay fails too
  • a token request for another resource returns invalid_target (RFC 8707)
  • an unregistered redirect_uri gets a 400 and no redirect at all
  • a reused refresh token kills the whole token family
  • five wrong passwords on the consent page get you a 429

The audience one is my favourite because it's easy to get wrong. Same JWT secret, different public URL, so the token has to be refused:

// Same secret, different deployment URL => different audience and issuer.
const { app: other } = makeApp({ PUBLIC_URL: 'http://127.0.0.1:9999' });
expect((await call(tokens.access_token, other)).status).toBe(401);
Enter fullscreen mode Exit fullscreen mode

The Python side does the same thing against two real servers:

async def test_forged_and_foreign_tokens_rejected(server_factory) -> None:
    a = server_factory()
    b = server_factory()
    _, tokens = sign_in(a.base)
    for base, token in [(a.base, "forged"), (b.base, tokens["access_token"])]:
        r = httpx2.post(f"{base}/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}},
                        headers={"authorization": f"Bearer {token}", "accept": "application/json, text/event-stream"})
        assert r.status_code == 401
Enter fullscreen mode Exit fullscreen mode

Rule 4: scopes need a 403, not a 401

If a token is valid but missing a scope, the right answer is 403 with error="insufficient_scope", so the client can ask the user to consent again. A 401 makes it look like the login broke.

My notes_clear tool needs notes:admin, and the test wraps fetch with a spy so it can read the raw challenge:

await expect(basicClient.callTool({ name: 'notes_clear', arguments: {} }))
  .rejects.toMatchObject({ requiredScope: 'notes:admin' });
const challenge = seen.find((r) => r.status === 403);
expect(challenge?.headers.get('www-authenticate')).toContain('error="insufficient_scope"');

// Sign in again with the extra scope and it works.
const admin = await signIn(app, 'mcp notes:admin');
Enter fullscreen mode Exit fullscreen mode

Rule 5: pin the tool contract

I keep one test that lists tools and checks the exact names. It's boring, but it catches a tool that disappears because of a config change or a bad import:

names = sorted(t.name for t in (await client.list_tools()).tools)
assert names == ["notes_add", "notes_clear", "notes_search", "whoami"]
Enter fullscreen mode Exit fullscreen mode

For tools that call out to other systems, I check the error shape too. My trigger_workflow tool (an n8n/Make/Zapier bridge) has to:

  • mark a non-2xx webhook reply as isError: true instead of pretending it worked
  • refuse a raw URL in place of a workflow name, without making any request
const bad = await client.callTool({ name: 'trigger_workflow', arguments: { workflow: 'https://evil.example', payload: {} } });
expect(bad.isError).toBe(true);
expect(calls).toHaveLength(1); // the fake fetch was never hit again
Enter fullscreen mode Exit fullscreen mode

Tool errors should come back as tool results the model can read. Exceptions that kill the session aren't good enough.

Rule 6: test the boring HTTP stuff

These cost five minutes each and stop real attacks:

  • a foreign Host header gets 403 (DNS rebinding)
  • a foreign browser Origin gets 403
  • CORS preflight works for allowed origins and exposes WWW-Authenticate (if it doesn't, browser clients can't see the challenge)
  • the consent page sends no-store, X-Frame-Options: DENY and frame-ancestors 'none'
  • config refuses http:// public URLs, short JWT secrets and AUTH_MODE=none on a public URL

The config guards are plain unit tests with no server needed, and they've saved me from a bad deploy more than once.

Rule 7: at least one test over a real socket

In-process tests are great, but one test should boot the actual entry point on TCP and do the full sign-in. In Python every test already does this (uvicorn on a free port in a background thread). In TypeScript, one test boots src/node.ts, runs discovery, OAuth and a tool call over the network, then checks that a forged token gets 401. There's also one for the stdio entry, because Claude Desktop users still run it locally.

Rule 8: smoke test the live URL after every deploy

Tests prove the code works. They don't prove the deployment works: env vars, KV bindings, the public URL, a proxy eating headers. So after each deploy I run a script against the live server:

npm run smoke -- https://my-mcp.example.workers.dev 'owner password'
Enter fullscreen mode Exit fullscreen mode

It does exactly what a connector does and stops at the first failure:

✔ 401 + WWW-Authenticate resource_metadata
✔ discovery: PRM -> https://my-mcp.example.workers.dev
✔ dynamic client registration
✔ consent + authorization code
✔ token exchange (PKCE verified)
✔ tools/list: ...
✔ tools/call whoami: ...
✔ refresh token rotation
Enter fullscreen mode Exit fullscreen mode

It's plain HTTP, so it works against the Python server too.

Rule 9: then poke it by hand with MCP Inspector

Last step, I open the official Inspector and click around:

npx @modelcontextprotocol/inspector
Enter fullscreen mode Exit fullscreen mode

Pick Streamable HTTP, paste the URL, and read the tool descriptions the way a model would. One gotcha: the Inspector runs in a browser, so its origin (e.g. http://localhost:6274) has to be in ALLOWED_ORIGINS, or the Origin check from Rule 6 will block it. That's a good sign the check works.

The short version

  1. Test through a real MCP client.
  2. Assert the 401 challenge and metadata.
  3. Write more "should fail" auth tests than happy-path ones.
  4. Missing scope means 403 insufficient_scope.
  5. Pin tool names and error shapes.
  6. Cover Host, Origin, CORS and security headers.
  7. Boot it over a real socket once.
  8. Smoke test the live URL after deploy.
  9. Finish with the Inspector.

None of this is fancy. It's just testing the parts that real clients actually hit.


All the tests above come from my TypeScript + Python remote MCP template (OAuth 2.1 + PKCE, dynamic client registration, scoped tools, approval gates). If you want the suite and the smoke script ready to go, it's the Remote MCP Connector Kit.

Top comments (0)