Developer Tooling

Test Read-Only MCP Tools for Data Access Leaks

A conceptual map connects Read a doc with Validate input, Check access, Limit bytes.

A read-only MCP tool can still return information its caller should never receive. The absence of a delete operation says nothing about whether a document reader can expose internal notes, accept an arbitrary file path, or produce an unbounded response.

To test that boundary, call the tool through an MCP client with both permitted and rejected inputs. Assert the returned content, error behavior, and output limits. A successful connection and a green test for one public document are only the beginning.

This tutorial builds a small documentation reader and exercises it through a real child process over standard input and output. You will inspect the access policy, run 13 deterministic tests, and distinguish useful evidence from claims the tests cannot establish. Everything uses synthetic documents. No account, API key, AI model, or access to private files is required.

The topic is especially relevant as MCP tooling evolves. The July 2026 MCP specification release (opens in a new tab) included authorization changes alongside a revised protocol core. That development makes a good reason to revisit integrations, but a newer SDK does not write an application’s access policy for it.

Define the boundary before writing the handler

Our tool, get_public_doc, accepts a document ID and returns one approved document. The ID identifies an entry in an application-owned catalogue. It is never interpreted as a file path, URL, shell argument, or database expression.

The catalogue has four synthetic entries. Two contain short demonstration documentation. One contains deliberately oversized text so we can exercise the response limit. The final entry, internal-notes, contains a recognizable private-test marker. That entry is intentionally absent from the export allowlist.

Keeping a private fixture in the same catalogue helps demonstrate why “the record exists” and “the record may be returned” are different checks. It is not a recommendation to store real secrets in a distributable package. The repository contains no real private documents.

Request Required behavior
getting-started Return the exact approved document.
internal-notes Return DOCUMENT_NOT_AVAILABLE without private content.
An unknown, well-formed ID Return the same application error.
A relative path, absolute path, or URL Reject the input schema.
A permitted ID plus an extra path field Reject the input schema.
oversized-fixture Return DOCUMENT_TOO_LARGE.
A different tool name Return a protocol error.

This policy is a public export rule shared by every caller. It is not a multi-user authorization system. If different people should see different documents, the policy must also consider a verified caller identity and that person’s permissions. A public allowlist cannot substitute for those checks.

If you are new to registering tools, read our MCP server implementation guide (opens in a new tab) first. Here, the focus is proving what an already-defined tool will refuse to do.

Get the tested example running

The complete example and tests (opens in a new tab) are available in the Emminex developer-examples repository. You need Git, npm, and Node.js 22 or newer. The verification for this article used Node.js 22.18.0, the MCP server and client packages at version 2.4.0, and Zod 4.6.7 on macOS.

git clone https://github.com/emminextechdocs/developer-examples.git
cd developer-examples/mcp-readonly-boundaries
node --version
npm ci
npm test
npm run demo

Use npm ci with the committed lockfile. The dependency versions in this example are a reproducibility record, not a promise that those versions will remain the latest or appropriate indefinitely. Review dependency advisories before reusing the project in a deployed service.

The tests launch and close their own server process. You do not need to start npm start in another terminal. After dependencies are installed, neither the test suite nor the demo needs an external API. The server reads its fixed module catalogue and answers local protocol requests.

The demo performs three requests: a permitted read, a rejected private ID, and an oversized public fixture. Its output is intentionally compact so you can compare the behavior with the policy table. A plain npm start instead waits for protocol input; an apparently idle terminal is expected in that mode.

The important files are catalogue.mjs, policy.mjs, factory.mjs, server.mjs, and test/boundaries.test.mjs. This separation keeps the export decision visible instead of burying it inside transport setup or an agent prompt.

Use a strict input schema without confusing it with authorization

The server declares one required field. This is the input schema from factory.mjs:

const inputSchema = z.strictObject({
  documentId: z.string().min(1).max(64).regex(/^[a-z0-9-]+$/),
});

The chosen ID alphabet allows lowercase letters, numbers, and hyphens. Slash characters, dots, colons, and empty values fall outside that contract. We do not trim or normalize input into a different ID, so callers must provide the identifier exactly as documented.

The strict object also rejects fields that the tool never promised to accept. For example, a caller cannot add path: '../internal-notes' beside a valid ID and have that extra input silently become part of a future code path. Zod documents this behavior in its object schema reference (opens in a new tab).

Schema validation answers whether an argument has an allowed shape. internal-notes has the right shape, so the schema alone cannot establish that it is public. The separate allowlist makes that decision. This is the distinction the private-ID test is designed to preserve during later refactoring.

Do not broaden the schema just because a model supplies an unexpected input. First decide whether the reader actually needs that capability. Accepting URLs would create a different tool with different network, content, and authorization concerns. Accepting paths would create a different filesystem interface. Neither is necessary to read this small published catalogue.

Enforce the export policy in ordinary application code

policy.mjs checks membership before obtaining or serializing the document. The main decision is small enough to inspect directly:

export function readPublicDocument(documentId) {
  if (!publicDocumentIds.has(documentId)) {
    return failure('DOCUMENT_NOT_AVAILABLE',
      'Choose a public document ID from the tool description.');
  }
  const doc = catalogue.get(documentId);
  if (!doc) {
    return failure('DOCUMENT_NOT_AVAILABLE',
      'Choose a public document ID from the tool description.');
  }
  const text = JSON.stringify({
    documentId, title: doc.title, body: doc.body,
  });
  if (Buffer.byteLength(text, 'utf8') > MAX_CONTENT_BYTES) {
    return failure('DOCUMENT_TOO_LARGE',
      'This document exceeds the export limit. Ask the maintainer for a smaller published section.');
  }
  return { content: [{ type: 'text', text }] };
}

The shared failure helper returns isError: true and JSON text containing a code and a readable message. It does not echo the private document’s content. The unknown-ID and private-ID branches return the same application result, avoiding an explicit “this private document exists” response.

That equality is a limited guarantee. The fixture does not test timing differences or every possible indirect signal. It verifies the response that the client receives for the two concrete cases. Keep the claim at that level instead of describing the implementation as immune to enumeration.

Notice that the function never passes caller input to a filesystem operation. There is no directory traversal problem to solve inside this handler because it does not resolve paths at all. The path-shaped tests still matter: they protect the narrow interface from accidentally expanding into a generic reader later.

The allowlist is part of the application release. Adding an ID should receive the same review as adding a publicly accessible endpoint. Review the document’s contents, its intended audience, and its size before exporting it. A readable identifier is not itself permission to reveal a record.

Bound the returned text in bytes

MAX_CONTENT_BYTES is 4,096. The check measures the UTF-8 byte length of the serialized document object, including the ID, title, and body fields. It does not measure JavaScript string length, model tokens, total process memory, or the complete JSON-RPC envelope.

Those distinctions matter. A limit that protects one resource should not be advertised as protecting every resource. The server already holds its synthetic catalogue in memory, so checking the output length does not prevent memory use while loading that catalogue. A database-backed implementation would need limits on what it fetches as well as what it returns.

The fixture uses 2,000 repetitions of 界 in its oversized document. Its JavaScript string length is below 4,096, while its UTF-8 representation is above that threshold. The test therefore catches a common mistake: replacing the byte-length check with text.length. Node’s Buffer reference (opens in a new tab) explains the encoding-aware measurement used here.

We reject the large document instead of silently truncating it. Truncation could remove a prerequisite, warning, closing JSON delimiter, or qualifying sentence. For real documentation, a better next step is often an explicitly published smaller section with its own ID. If you introduce pagination or excerpts, define their boundaries and incompleteness clearly.

The error message remains small and explains the next action. It does not return the first several thousand bytes of a document that the policy has refused to export.

Connect through the actual stdio entry point

The production entry point is deliberately short:

import { serveStdio } from '@modelcontextprotocol/server/stdio';
import { createServer } from './factory.mjs';

serveStdio(createServer);

The SDK’s stdio guide (opens in a new tab) documents the factory-based entry point. Standard output belongs to protocol messages. Ordinary startup messages written there can break the client’s parsing, so this example does not print them. Diagnostic messages, if added, belong on standard error and should exclude document bodies and credentials.

The test helper creates a separate process with the same Node executable as the test runner:

const transport = new StdioClientTransport({
  command: process.execPath,
  args: [fileURLToPath(new URL('./server.mjs', import.meta.url))],
  env: {},
  stderr: 'pipe',
});
const client = new Client(
  { name: 'boundary-test-client', version: '1.0.0' },
  { versionNegotiation: { mode: 'auto' } },
);
await client.connect(transport);

The imports and cleanup live in client.mjs; the official client connection guide (opens in a new tab) covers these transport APIs. The empty environment override does not mean the child is an operating-system sandbox: the SDK has its own default environment handling, and the process still runs with the launching user’s privileges.

Using an absolute script path avoids depending on the caller’s working directory. Closing the client in the test cleanup also prevents the suite from leaving an idle server behind. This integration layer can catch entry-point and protocol failures that direct calls to readPublicDocument() would miss.

Assert denied calls as carefully as successful calls

The positive test checks the exact approved document, not just a nonempty response. Otherwise a handler that returns the wrong document could still pass. It also checks the measured payload size.

The private-document test makes a different assertion:

const privateResult = await read('internal-notes');
const missingResult = await read('missing-doc');
assert.equal(privateResult.isError, true);
assert.deepEqual(privateResult, missingResult);
assert.equal(body(privateResult).code, 'DOCUMENT_NOT_AVAILABLE');
assert.doesNotMatch(
  JSON.stringify(privateResult), /PRIVATE_FIXTURE_DO_NOT_EXPORT/,
);

The recognizable marker makes an accidental export visible without using a real secret. Comparing responses verifies the deliberately shared failure behavior. A test that only checks isError would miss a handler that reports failure while still including private content in an error detail.

The suite also sends a relative path, an absolute path, a URL, a numeric ID, an oversized ID, and an extra field. These requests go through client.callTool(), so the checks exercise the registered schema rather than only a helper function.

In the pinned SDK, those invalid argument shapes return tool results with isError: true. An unknown tool name instead rejects the call as a protocol error. The SDK error guide (opens in a new tab) explains the distinction. Do not write one generic assertion that accepts any failure: a disconnected child process is not evidence that your private-document policy worked.

A final permitted read follows the rejected requests. This catches the misleading situation where every negative test appears to succeed because the server has stopped responding usefully. The expected result is a live server that refuses the wrong inputs and still answers the right ones.

Read the test results without overstating them

The verification run completed all 13 tests successfully. The suite covers tool discovery, the exact approved response, private and missing IDs, six invalid-input forms, the UTF-8 size limit, an unknown tool, recovery after rejected calls, and unchanged catalogue contents after direct policy calls.

ℹ tests 13
ℹ suites 0
ℹ pass 13
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0

This is a functional regression suite for the supplied implementation. It is not a penetration-test report, a guarantee against dependency compromise, or proof that an AI host will always interpret returned text correctly. There is no benchmark or production-traffic claim attached to the result.

The catalogue immutability check is similarly specific: it compares the local synthetic catalogue before and after direct policy calls. The protocol tests exercise a separate child process. Together they provide useful checks, but they do not monitor every possible filesystem or network side effect of arbitrary future dependencies.

Two deliberate mutation checks also confirmed that the suite detects the intended regressions. Removing the allowlist check made the private-document test fail. Replacing UTF-8 byte measurement with string length made the oversized-document test fail. Both changes were restored before the final passing run; the mutation results are recorded with the example.

When adapting the example, keep the rejection tests even if they seem repetitive. Each protects a distinct contract. Removing the allowlist, permitting extra arguments, or replacing byte measurement with string length should be a deliberate review decision that is visible in tests, not an incidental refactor.

Keep read-only annotations separate from real enforcement

The tool advertises readOnlyHint: true and openWorldHint: false. These describe the example’s intended behavior. They do not prevent a handler from writing files, contacting another service, or returning confidential data.

The MCP project’s discussion of tool annotations (opens in a new tab) explicitly treats these values as hints whose usefulness depends on trust. In this example, the actual restrictions are the schema, the allowlist, the fixed catalogue, and the response-size decision. Changing an annotation alone would not strengthen those checks.

There is also a difference between validating a request and trusting a result. A public document may contain a code sample, quotation, or malicious instruction. Returning it as text does not prove that a model will treat it appropriately. The fixture tests transport and access behavior without involving a model, so it makes no prompt-injection-resistance claim.

If you later connect a repository, help desk, or web crawler, review where its text came from and how the host uses it. Keep content separate from executable configuration. A successful allowlist check should authorize reading a document, not executing instructions found inside it.

Adapt the design for private or remote documentation

The local fixture has no login because it exports public synthetic content to its launcher. Moving the same code to a shared HTTP service changes the trust boundary. Network reachability, a guessed document ID, and a tool description are not identities.

The MCP authorization guide (opens in a new tab) distinguishes HTTP authorization from credentials used by local stdio servers. For a private service, determine who the caller is, which documents that identity may access, and how upstream permissions are preserved. Our OAuth PKCE guide (opens in a new tab) provides background for interactive native clients; it is not a complete MCP authorization implementation.

A document cache needs the same review. If content varies by tenant or user, a cache keyed only by document ID can return a previous caller’s result to the wrong person. Define the authorization scope of cached content and test two callers with different permissions before introducing shared caching.

For file-backed storage, replace the fixed catalogue only after defining an explicit export process. Prefer publishing approved material into a separate collection over giving the tool broad access to a user’s home directory. If storage can change while requests run, test deletion, permission changes, and stale entries as separate behaviors.

Keep the tool description, policy, tests, and operator instructions together. The workflow in our docs-as-code guide (opens in a new tab) helps make contract changes reviewable alongside implementation changes. A reviewer should be able to see exactly which additional data becomes accessible in a release.

Troubleshoot the first local run

If npm ci fails, check the Node version and whether you are inside mcp-readonly-boundaries, where the lockfile lives. Do not mix installation commands from an older SDK tutorial into this package; this example uses the split v2 server and client packages.

If the process waits without printing a document, confirm which command you ran. npm start launches a server that expects MCP input. npm run demo launches a client and produces the three demonstration results. They have different jobs.

If the private-ID test starts returning content, inspect the allowlist before changing the expected output. The expected rejection is part of the exercise’s policy. If only the oversized fixture fails, compare UTF-8 byte measurement with string length and inspect which serialized fields are counted.

If a protocol test hangs or reports malformed messages, look for ordinary logging on standard output and confirm the configured server path. Keep the child’s standard error separate from the protocol stream. Fix the connection problem before interpreting any failed call as a successful access-control check.

Frequently asked questions

Does read-only mean an MCP tool is safe?

It describes an absence of intended mutation, not a permission model. A read-only operation can disclose data. Test which records it returns, what inputs it accepts, and what it refuses, then assess process permissions and the host separately.

Do I need an AI subscription to run these tests?

No. The included client sends deterministic protocol calls directly to the local server. That verifies the supplied request and response behavior without a model. Evaluating how a particular host chooses tools or interprets their content is a separate activity.

Why not accept a file path and clean it up?

The task only needs approved document IDs. A path parameter would expose a broader interface and require additional filesystem policy. The fixed mapping keeps that unnecessary capability out of the example entirely.

Is 4,096 bytes an MCP protocol limit?

No. It is this application’s chosen limit for the successful JSON text payload. The protocol envelope adds overhead, and byte count does not equal model token count. Choose and document limits that match your own documents and operational needs.

Can I deploy this example as a private company knowledge server?

Use it as a tested starting point for a narrow public export, not as a completed private service. Caller authentication, per-document authorization, tenant isolation, storage behavior, deployment controls, and host-level evaluations are outside this fixture’s implementation.

Start a conversation

Ready to improve your developer documentation?

Tell us what developers need to accomplish and where the current experience falls short.

Expect a reply within one business day.