Building an MCP Search Tool Without Giving It the Whole Database
An assistant can search candidate records. Should that mean it can see every department?

An assistant can search candidate records. Should that mean it can see every department?
The interesting part of this integration is not getting a tool call to return JSON. It is deciding which records that call may return. We'll use a small candidate-search server to connect the MCP contract to input validation, server-owned permissions, and a transport the host can actually use.
Target an explicit SDK and protocol revision
An MCP host manages the application, model, and consent UI. Its MCP clients connect to servers that expose tools, resources, and prompts. Read tools can disclose confidential data; they are not automatically low risk.
Examples are illustrative, not claims of deployed production behavior.
The current stable TypeScript SDK is v2, with separate @modelcontextprotocol/server and @modelcontextprotocol/client packages. The older @modelcontextprotocol/sdk v1 line remains maintained but does not implement the 2026-07-28 specification. This example uses v2 and Zod 4; do not mix the two SDK generations.
Validate and authorize a bounded tool
The synthetic fixture actually filters query, department, and limit. Allowed departments come from trusted server context, not tool arguments. A schema validates shape; it does not grant access. Replace fixtures with parameterized database queries that enforce tenant and row policy before limiting results. readOnlyHint is advisory metadata, not an access-control boundary.
// search-server.ts: synthetic records, local demonstration only
import { McpServer } from "@modelcontextprotocol/server";
import * as z from "zod/v4";
const Department = z.enum(["Engineering", "Design"]);
export type Department = z.infer<typeof Department>;
const Record = z.object({
id: z.string(),
role: z.string(),
department: Department,
});
const records: z.infer<typeof Record>[] = [
{ id: "example-1", role: "Platform Engineer", department: "Engineering" },
{ id: "example-2", role: "Product Designer", department: "Design" },
];
export function createSearchServer(allowedDepartments: ReadonlySet<Department>) {
const server = new McpServer({ name: "candidate-search-demo", version: "1.0.0" });
server.registerTool("search_candidates", {
description: "Search the authorized subset of synthetic candidate records.",
inputSchema: z.object({
query: z.string().trim().min(2).max(200),
limit: z.number().int().min(1).max(20).default(5),
department: Department.optional(),
}).strict(),
outputSchema: z.object({ results: z.array(Record) }),
annotations: { readOnlyHint: true },
}, async ({ query, limit, department }) => {
if (department && !allowedDepartments.has(department)) {
return {
isError: true,
content: [{ type: "text", text: "Access to the requested department is denied." }],
};
}
const results = records.filter((record) =>
allowedDepartments.has(record.department) &&
(!department || record.department === department) &&
record.role.toLowerCase().includes(query.toLowerCase())
).slice(0, limit);
return {
content: [{ type: "text", text: JSON.stringify({ results }) }],
structuredContent: { results },
};
});
return server;
}Notice the order inside the filter. A record must belong to an allowed department before the query can match it, and the result limit comes last. Asking for a larger limit never widens the caller's permitted set of records.
Serve the local demonstration
Use this entry point for a local host-launched process. Its fixed Engineering permission is a demonstration policy, not user authentication. Keep logs on stderr because stdout carries protocol messages. Real credentials belong in a protected environment or credential store, never in model-visible tool results.
// main.ts: launch through an MCP host, not inside a browser
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { createSearchServer, type Department } from "./search-server";
serveStdio(() => createSearchServer(new Set<Department>(["Engineering"])));
console.error("Synthetic search server listening on stdio.");Remote transport and access tokens
Use Streamable HTTP for a remote endpoint; legacy HTTP+SSE is a compatibility transport, not the current recommendation. Streamable HTTP can itself use SSE for a response. The 2026-07-28 revision uses per-request protocol metadata, unlike earlier initialization-scoped sessions; use current SDK serving helpers rather than transplanting v1 session maps.
For protected HTTP deployments, implement the documented OAuth resource-server flow. Validate access-token signature or introspection, issuer, audience/resource, expiry, and scopes. An identity JWT is not automatically an MCP access token. Do not pass an MCP bearer token unchanged to downstream services; obtain separate appropriately scoped credentials. Apply Origin/Host validation, TLS, per-principal limits, and authorization on every call.
Operational checks
Test invalid arguments, empty results, forbidden departments, oversized limits, cross-tenant access, and revoked credentials. Distinguish tool failures (isError) from protocol errors; never return a success-shaped placeholder after a database failure. Audit minimal decision metadata without copying candidate data or secrets. Mutations need server-enforced authorization, explicit approval where required, and replay/idempotency controls even if a host shows a confirmation dialog.
A useful search tool exposes a narrow operation, not a shortcut around the application's permissions. Start with the authorized subset of records, then apply the search. That order matters more than how convincing the assistant's request sounds.