MCP Server RBAC, Tool Composition, and Multi-Agent Workflow Patterns
Enterprise patterns for Model Context Protocol: tool composition, multi-agent orchestration, role-based access control, and production observability.
Most MCP material stops at the first working server: register a few tools, connect a client, done. The failure modes start later, when a second team connects to the same server and one of the registered tools can change production.
Six patterns cover that gap: tool annotations, workflow orchestration, RBAC with attribute conditions, progressive authorization, error recovery, and observability. If you adopt only one, make it RBAC backed by audit logging, with the user’s identity taken from a validated OAuth token. Permissions and audit trails are the layers that hurt to retrofit once agents are already calling tools, while orchestration can wait until you have two workflows to compare.
The Scaling Challenge#
Organizations successfully deploying basic MCP integrations encounter predictable challenges as they scale:
Tool Explosion: Starting with 5 tools and growing to 50 across 10 servers creates discovery and selection problems for agents.
Permission Complexity: Different users need different tool access. A junior developer should not trigger production deployments, but how do you implement fine-grained access control?
Workflow Orchestration: Complex tasks require multiple tools in sequence or parallel. Coordinating tool chains reliably becomes its own engineering problem.
Multi-Agent Coordination: Multiple AI agents working together need different tool subsets. Preventing conflicts and ensuring proper isolation requires careful design.
Audit and Compliance: Regulated industries need complete audit trails. Tracking who invoked what, when, and with what results is non-negotiable.
Pattern 1: Tool Design and Annotation#
Well-designed MCP tools share common characteristics that make them composable and maintainable. Tool annotations describe behavior to clients: whether a tool writes, whether a repeated call is safe, and whether it reaches external systems. Clients can use them to decide which calls to show to a human before they run.
Note
These patterns follow MCP specification 2025-06-18, with one addition from the 2025-11-25 revision: the insufficient_scope step-up flow in Pattern 4. The same revision also moves input validation errors from protocol errors to tool execution errors. The code uses the TypeScript SDK’s registerTool; the older server.tool() overloads are deprecated.
Comprehensive Tool Annotations#
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
const server = new McpServer({
name: "deployment-server",
version: "1.0.0",
});
// Tool with comprehensive annotations
server.registerTool(
"deploy_service",
{
title: "Deploy Service",
description: "Triggers deployment of a service to the specified environment",
inputSchema: {
service: z.string().describe("Service name to deploy"),
environment: z.enum(["staging", "production"]).describe("Target environment"),
version: z.string().regex(/^\d+\.\d+\.\d+$/).describe("Semantic version"),
},
annotations: {
// Behavioral hints for clients (MCP specification 2025-06-18)
readOnlyHint: false, // This tool modifies state
destructiveHint: true, // Replaces the running version; undoing it takes another deploy
idempotentHint: false, // Multiple calls create multiple deployments
openWorldHint: true, // Interacts with external systems
},
},
async ({ service, environment, version }) => {
// Implementation with proper error handling
const result = await deploymentService.deploy(service, environment, version);
return {
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
};
}
);
Warning
Annotations are hints, not guarantees. The specification says clients “MUST consider tool annotations to be untrusted unless they come from trusted servers”, so a client cannot base a security decision on a hint from a server it does not control. On your own servers, mark anything that changes production as destructive. destructiveHint: false tells clients the tool performs only additive updates, and a client that confirms only destructive calls would let the deploy through without asking. The authorization decision itself stays on the server (Pattern 3).
Output Schemas for Structured Results#
Tools that return structured data benefit from output schemas, enabling programmatic result handling.
Note
outputSchema and structuredContent arrived with the 2025-06-18 specification. In the TypeScript SDK, outputSchema exists only in the registerTool config; the deprecated server.tool() overloads read a third object argument as plain annotations.
server.registerTool(
"get_service_metrics",
{
title: "Get Service Metrics",
description: "Retrieves performance metrics for a service",
inputSchema: {
service: z.string(),
timeRange: z.enum(["1h", "24h", "7d", "30d"]),
},
// Output schema enables structured content validation
outputSchema: {
service: z.string(),
period: z.string(),
metrics: z.object({
requestCount: z.number(),
errorRate: z.number(),
p50Latency: z.number(),
p99Latency: z.number(),
}),
},
annotations: {
readOnlyHint: true,
idempotentHint: true,
},
},
async ({ service, timeRange }) => {
const metrics = await metricsService.getMetrics(service, timeRange);
return {
content: [{ type: "text", text: JSON.stringify(metrics) }],
// Structured content for programmatic access
structuredContent: metrics,
};
}
);
Tool Composition Patterns#
Complex operations often require chaining multiple tools. Here are patterns that work:
// Pattern 1: Sequential Tool Chain Configuration
const deploymentChain = {
chain: [
{
tool: "validate_config",
inputPath: "$.config",
outputPath: "$.validation",
},
{
tool: "run_tests",
inputPath: "$.validation.service",
outputPath: "$.testResults",
},
{
tool: "deploy_service",
inputPath: "$.validation",
outputPath: "$.deployment",
},
],
};
// Pattern 2: Parallel Tool Execution
const healthCheckConfig = {
parallel: [
{ tool: "check_service_health", params: { service: "api" } },
{ tool: "check_service_health", params: { service: "database" } },
{ tool: "check_service_health", params: { service: "cache" } },
],
merge: "$.healthStatus", // Combine results
};
// Pattern 3: Conditional Tool Execution
const conditionalDeployConfig = {
condition: "$.environment === 'production'",
ifTrue: [
{ tool: "get_deployment_approval" },
{ tool: "notify_stakeholders" },
{ tool: "deploy_service" },
],
ifFalse: [
{ tool: "deploy_service" },
],
};
Pattern 2: Multi-Agent Workflow Orchestration#
When multiple AI agents need to collaborate with different tool access, an orchestrator pattern provides coordination and isolation.
Orchestrator Implementation#
Note
The HTTP+SSE transport is deprecated. New clients use the Streamable HTTP transport (StreamableHTTPClientTransport).
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
interface AgentConfig {
name: string;
role: string;
servers: string[];
permissions: string[];
}
interface WorkflowStep {
name: string;
agent: string;
tool: string;
params: Record<string, any>;
outputKey: string;
timeout?: number;
onError: "abort" | "continue" | "rollback";
parallel?: WorkflowStep[];
}
class MultiAgentOrchestrator {
private agents: Map<string, AgentConfig> = new Map();
private mcpClients: Map<string, Client> = new Map();
async registerAgent(config: AgentConfig): Promise<void> {
const client = new Client({
name: `agent-${config.name}`,
version: "1.0.0",
});
// Connect to assigned MCP servers
for (const serverUrl of config.servers) {
await client.connect(new StreamableHTTPClientTransport(new URL(serverUrl)));
}
// Filter available tools based on agent permissions
const { tools } = await client.listTools();
const allowedTools = tools.filter(tool =>
this.checkToolPermission(tool, config.permissions)
);
console.log(`Agent ${config.name} registered with ${allowedTools.length} tools`);
this.agents.set(config.name, config);
this.mcpClients.set(config.name, client);
}
async executeWorkflow(workflow: WorkflowDefinition): Promise<WorkflowResult> {
const executionId = crypto.randomUUID();
const results: Map<string, any> = new Map();
console.log(`Starting workflow ${workflow.name} (${executionId})`);
for (const step of workflow.steps) {
try {
if (step.parallel) {
// Execute parallel steps concurrently
const parallelResults = await Promise.all(
step.parallel.map(subStep =>
this.executeStep(subStep, results, executionId)
)
);
// Merge parallel results
parallelResults.forEach((result, index) => {
results.set(step.parallel[index].outputKey, result);
});
} else {
// Execute sequential step
const result = await this.executeStep(step, results, executionId);
results.set(step.outputKey, result);
}
} catch (error) {
if (step.onError === "continue") {
console.log(`Step ${step.name} failed, continuing: ${error.message}`);
results.set(step.outputKey, { error: error.message });
} else if (step.onError === "rollback") {
await this.rollbackWorkflow(executionId, results);
throw error;
} else {
throw error;
}
}
}
return {
executionId,
status: "completed",
results: Object.fromEntries(results),
};
}
private async executeStep(
step: WorkflowStep,
context: Map<string, any>,
executionId: string
): Promise<any> {
const agent = this.agents.get(step.agent);
const client = this.mcpClients.get(step.agent);
if (!agent || !client) {
throw new Error(`Agent ${step.agent} not found`);
}
// Resolve parameters from workflow context
const params = this.resolveParams(step.params, context);
// Verify permission before execution
if (!this.checkToolPermission({ name: step.tool }, agent.permissions)) {
throw new Error(`Agent ${step.agent} lacks permission for tool ${step.tool}`);
}
// Execute with timeout; on expiry the SDK cancels the request
// and sends notifications/cancelled to the server
const result = await client.callTool(
{ name: step.tool, arguments: params },
undefined,
{ timeout: step.timeout ?? 30000 }
);
// Audit logging
await this.auditLog({
executionId,
agent: step.agent,
tool: step.tool,
params,
result: result.isError ? "failure" : "success",
timestamp: new Date().toISOString(),
});
if (result.isError) {
throw new Error(`Tool ${step.tool} failed: ${result.content[0]?.text}`);
}
return result.content;
}
private checkToolPermission(
tool: { name: string },
permissions: string[]
): boolean {
// Permission format: "tool:*", "tool:read", "tool:deploy:staging"
for (const perm of permissions) {
if (perm === "tool:*") return true;
if (perm === `tool:${tool.name}`) return true;
if (perm.startsWith(`tool:${tool.name}:`)) return true;
}
return false;
}
}
Workflow Definition Example#
const productionDeploymentWorkflow: WorkflowDefinition = {
name: "production-deployment",
steps: [
{
name: "validate",
agent: "validator",
tool: "validate_deployment_config",
params: { service: "$.input.service", version: "$.input.version" },
outputKey: "validation",
onError: "abort",
},
{
name: "parallel-checks",
parallel: [
{
name: "health-check",
agent: "health-checker",
tool: "check_service_health",
params: { service: "$.input.service" },
outputKey: "health",
onError: "abort",
},
{
name: "security-scan",
agent: "security-scanner",
tool: "scan_vulnerabilities",
params: { version: "$.input.version" },
outputKey: "security",
onError: "abort",
},
],
onError: "abort",
},
{
name: "get-approval",
agent: "approval-bot",
tool: "request_deployment_approval",
params: {
service: "$.input.service",
validation: "$.validation",
security: "$.security",
},
outputKey: "approval",
timeout: 300000, // 5 minutes for human approval
onError: "abort",
},
{
name: "deploy",
agent: "deployer",
tool: "deploy_service",
params: {
service: "$.input.service",
version: "$.input.version",
approvalId: "$.approval.id",
},
outputKey: "deployment",
onError: "rollback",
},
],
};
Pattern 3: Role-Based Access Control#
Enterprise MCP deployments need fine-grained access control. Here is a pattern that combines RBAC with attribute-based conditions. It assumes the server already knows who is calling from a validated token; the integration below shows where that identity comes from.
Permission Model#
import { z } from "zod";
interface Permission {
resource: string; // "tool:deploy_service", "resource:config:*"
action: string; // "invoke", "read", "write"
conditions?: { // Optional ABAC conditions
environment?: string[];
timeWindow?: { start: string; end: string };
maxCost?: number;
};
}
interface Role {
name: string;
permissions: Permission[];
inherits?: string[]; // Role inheritance
}
export interface User {
id: string;
email: string;
roles: string[];
attributes: Record<string, any>;
}
RBAC Service Implementation#
export class MCPAuthorizationService {
private roles: Map<string, Role> = new Map();
constructor() {
this.initializeRoles();
}
private initializeRoles(): void {
// Define role hierarchy
const roles: Role[] = [
{
name: "viewer",
permissions: [
{ resource: "tool:list_*", action: "invoke" },
{ resource: "tool:get_*", action: "invoke" },
{ resource: "tool:check_*", action: "invoke" },
{ resource: "resource:*", action: "read" },
],
},
{
name: "developer",
inherits: ["viewer"],
permissions: [
{
resource: "tool:deploy_service",
action: "invoke",
conditions: { environment: ["development", "staging"] },
},
{ resource: "tool:run_tests", action: "invoke" },
{ resource: "tool:build_artifact", action: "invoke" },
],
},
{
name: "senior_developer",
inherits: ["developer"],
permissions: [
{
resource: "tool:deploy_service",
action: "invoke",
conditions: { environment: ["development", "staging", "production"] },
},
{ resource: "tool:rollback_deployment", action: "invoke" },
],
},
{
name: "admin",
permissions: [
{ resource: "*", action: "*" },
],
},
];
for (const role of roles) {
this.roles.set(role.name, role);
}
}
async authorize(
user: User,
tool: string,
params: Record<string, any>
): Promise<AuthorizationResult> {
const permissions = this.getEffectivePermissions(user);
let lastConditionFailure: string | undefined;
for (const perm of permissions) {
if (!this.matchesResource(perm.resource, `tool:${tool}`)) continue;
if (perm.action !== "*" && perm.action !== "invoke") continue;
// Check ABAC conditions
if (perm.conditions) {
const conditionResult = this.evaluateConditions(perm.conditions, params, user);
if (!conditionResult.allowed) {
// A failed condition rules out this permission only.
// Another role may still grant the call.
lastConditionFailure = conditionResult.reason;
continue;
}
}
return { allowed: true };
}
return {
allowed: false,
reason: lastConditionFailure ?? `User ${user.email} lacks permission for tool ${tool}`,
requiredElevation: this.suggestElevation(tool, params),
};
}
private getEffectivePermissions(user: User): Permission[] {
const permissions: Permission[] = [];
const processedRoles = new Set<string>();
const processRole = (roleName: string) => {
if (processedRoles.has(roleName)) return;
processedRoles.add(roleName);
const role = this.roles.get(roleName);
if (!role) return;
// Process inherited roles first (depth-first)
if (role.inherits) {
for (const inherited of role.inherits) {
processRole(inherited);
}
}
permissions.push(...role.permissions);
};
for (const roleName of user.roles) {
processRole(roleName);
}
return permissions;
}
private evaluateConditions(
conditions: Permission["conditions"],
params: Record<string, any>,
user: User
): { allowed: boolean; reason?: string } {
// Environment restriction
if (conditions?.environment) {
const requestedEnv = params.environment;
if (!conditions.environment.includes(requestedEnv)) {
return {
allowed: false,
reason: `Environment ${requestedEnv} not allowed. Permitted: ${conditions.environment.join(", ")}`,
};
}
}
// Time window restriction
if (conditions?.timeWindow) {
const now = new Date();
const hour = now.getHours();
const [startHour] = conditions.timeWindow.start.split(":").map(Number);
const [endHour] = conditions.timeWindow.end.split(":").map(Number);
if (hour < startHour || hour >= endHour) {
return {
allowed: false,
reason: `Operation only allowed between ${conditions.timeWindow.start} and ${conditions.timeWindow.end}`,
};
}
}
return { allowed: true };
}
private matchesResource(pattern: string, resource: string): boolean {
if (pattern === "*") return true;
// Escape regex metacharacters, then turn each * into .*
const regexPattern = pattern
.split("*")
.map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
.join(".*");
return new RegExp(`^${regexPattern}$`).test(resource);
}
}
The order of evaluation decides whether role inheritance works. getEffectivePermissions adds inherited permissions first, so a senior_developer sees the developer’s staging-only deploy_service grant before its own production grant. If a failed condition ended the loop with a denial, a senior developer could never deploy to production. The loop therefore skips a permission whose condition fails and denies only when no permission allows the call. The denial carries the last failed condition as its reason. matchesResource escapes regex metacharacters before expanding *, so a . in a pattern matches only a literal dot.
A test pins both behaviors (Node’s built-in test runner):
import { test } from "node:test";
import assert from "node:assert/strict";
import { MCPAuthorizationService, type User } from "./rbac.js";
const authz = new MCPAuthorizationService();
const user = (roles: string[]): User => ({ id: "u1", email: "dev@example.com", roles, attributes: {} });
test("senior_developer can deploy to production despite the inherited staging-only grant", async () => {
const result = await authz.authorize(user(["senior_developer"]), "deploy_service", { environment: "production" });
assert.equal(result.allowed, true);
});
test("developer is denied production with the condition as the reason", async () => {
const result = await authz.authorize(user(["developer"]), "deploy_service", { environment: "production" });
assert.equal(result.allowed, false);
assert.match(result.reason ?? "", /production not allowed/);
});
Secure MCP Server Integration#
The wrapper below never trusts the client to say who it is. Request _meta is metadata the client attaches to its own request. A server that read the user from it would let any client that sends { user: { roles: ["admin"] } } pass every check. The SDK hands each tool handler an authInfo object, and that object exists only when bearer-token middleware has validated the token (the wiring is in Pattern 4). AuthInfo has no subject field, so the token verifier you pass to requireBearerAuth copies the token’s sub claim into authInfo.extra.sub. Roles come from a server-side directory keyed by that subject.
import type { McpServer, ToolCallback } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { ShapeOutput } from "@modelcontextprotocol/sdk/server/zod-compat.js";
import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
import type {
CallToolResult,
ServerNotification,
ServerRequest,
ToolAnnotations,
} from "@modelcontextprotocol/sdk/types.js";
import type { ZodRawShape } from "zod";
type ToolExtra = RequestHandlerExtra<ServerRequest, ServerNotification>;
// Server-side source of truth for roles (IdP groups, a database table)
interface UserDirectory {
findBySubject(subject: string): Promise<User | undefined>;
}
class SecureMCPServer {
constructor(
private server: McpServer,
private authService: MCPAuthorizationService,
private users: UserDirectory,
private audit: AuditLogger
) {}
secureTool<Shape extends ZodRawShape>(
name: string,
config: {
title?: string;
description?: string;
inputSchema: Shape;
annotations?: ToolAnnotations;
},
handler: (args: ShapeOutput<Shape>, extra: ToolExtra) => Promise<CallToolResult>
) {
const wrapped = async (params: ShapeOutput<Shape>, extra: ToolExtra): Promise<CallToolResult> => {
// authInfo exists only after bearer-token middleware validated the token.
// Never read identity from extra._meta: the client writes that field.
const subject = extra.authInfo?.extra?.sub;
const user =
typeof subject === "string" ? await this.users.findBySubject(subject) : undefined;
if (!user) {
return {
content: [{ type: "text", text: "Authentication required" }],
isError: true,
};
}
// Check authorization
const authResult = await this.authService.authorize(user, name, params);
const resource = `tool:${name}`;
if (!authResult.allowed) {
await this.audit.record({ action: "tool_denied", user, resource, result: "denied", params });
return {
content: [{
type: "text",
text: `Access denied: ${authResult.reason}${
authResult.requiredElevation
? `\n${authResult.requiredElevation}`
: ""
}`,
}],
isError: true,
};
}
// Write-ahead: the invocation is durable before the tool runs.
// If the audit sink is down, this throws and the tool never executes.
await this.audit.record({ action: "tool_invoked", user, resource, result: "started", params });
const result = await handler(params, extra);
this.audit.log({
action: "tool_completed",
user,
resource,
result: result.isError ? "failure" : "success",
});
return result;
};
// ToolCallback<Shape> is a conditional type that TypeScript cannot resolve
// while Shape is still generic, so the wrapper is cast once here
this.server.registerTool(name, config, wrapped as ToolCallback<Shape>);
}
}
Both audit calls pass the raw params; the AuditLogger in Pattern 6 redacts them on the single path that builds an event.
Pattern 4: Progressive Authorization#
Instead of granting all permissions upfront, progressive authorization elevates scopes as needed for sensitive operations. MCP defines how this works over HTTP. The client obtains tokens for a signed-in user through the OAuth 2.1 authorization code flow with PKCE. When a call needs a scope the token lacks, the server answers 403 Forbidden with a WWW-Authenticate header that carries error="insufficient_scope" and the scopes the call requires. The client runs the authorization flow again for that scope set and retries the original request a limited number of times.
The client credentials grant does not fit here. It has no user, so there is no one to elevate, and a client that requests a higher scope for itself has approved its own request.
The server side is two Express middlewares in front of the MCP transport. The SDK’s requireBearerAuth validates the token and stores the result on req.auth, which the transport passes to tool handlers as authInfo. A second middleware maps each tools/call to the scope it needs and issues the challenge:
import express, { type Request, type Response, type NextFunction } from "express";
import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
// Scope a tools/call needs on top of the baseline read scopes
function requiredScope(tool: string, args: Record<string, unknown>): string | undefined {
switch (tool) {
case "deploy_service":
return args.environment === "production" ? "mcp:deploy:production" : "mcp:deploy:staging";
case "rollback_deployment":
return "mcp:deploy:production";
default:
return undefined;
}
}
function requireToolScopes(resourceMetadataUrl: string) {
return (req: Request & { auth?: AuthInfo }, res: Response, next: NextFunction) => {
const messages = Array.isArray(req.body) ? req.body : [req.body];
const granted = req.auth?.scopes ?? [];
for (const msg of messages) {
if (msg?.method !== "tools/call") continue;
const scope = requiredScope(String(msg.params?.name), msg.params?.arguments ?? {});
if (!scope || granted.includes(scope)) continue;
// Keep the scopes already granted so the new token does not lose them
const challenge = [...new Set([...granted, scope])].join(" ");
res
.status(403)
.set(
"WWW-Authenticate",
`Bearer error="insufficient_scope", scope="${challenge}", resource_metadata="${resourceMetadataUrl}"`
)
.json({ error: "insufficient_scope", error_description: `Requires ${scope}` });
return;
}
next();
};
}
const app = express();
const resourceMetadataUrl = "https://mcp.example.com/.well-known/oauth-protected-resource";
// Validate the token (signature, audience, expiry), then check per-tool scopes,
// then hand the request to the MCP transport (tokenVerifier and transport set up elsewhere)
app.post(
"/mcp",
express.json(),
requireBearerAuth({
verifier: tokenVerifier,
resourceMetadataUrl,
expectedResource: new URL("https://mcp.example.com/mcp"),
}),
requireToolScopes(resourceMetadataUrl),
(req: Request, res: Response) => transport.handleRequest(req, res, req.body)
);
Scopes and roles answer different questions. The scope says what this token was granted for; the RBAC check in Pattern 3 says whether this user may make the call at all. A call has to pass both.
The approval step and the token lifetimes belong to the authorization server, because it is the party that talks to the user and issues tokens:
| Scope | Minimum role | Approval | Token lifetime |
|---|---|---|---|
mcp:deploy:staging | developer | none | 3600 s (1 hour) |
mcp:deploy:production | senior_developer | tech lead or SRE on call | 1800 s (30 minutes) |
mcp:admin | admin | security team | 900 s (15 minutes) |
The authorization server holds a production request until an approver signs off, then issues a token with a short expires_in. The MCP server enforces the result on every request: requireBearerAuth rejects a token without an expiry time or past it with a 401, and requireToolScopes rejects a missing scope with a 403. When the short-lived token expires, the elevated scope goes with it, and there is no in-memory scope history to clean up.
Pattern 5: Error Handling and Recovery#
Production MCP deployments need robust error handling with retry strategies and circuit breakers.
Error Classification#
// JSON-RPC protocol errors: unknown tool, invalid request, server fault
enum JsonRpcErrorCode {
PARSE_ERROR = -32700,
INVALID_REQUEST = -32600,
METHOD_NOT_FOUND = -32601,
INVALID_PARAMS = -32602,
INTERNAL_ERROR = -32603,
}
// Internal classification of tool failures. These kinds drive retries and
// never go on the wire: the TypeScript SDK already uses -32000 and -32001.
type ToolFailureKind =
| "execution_failed"
| "timeout"
| "unauthorized"
| "rate_limited"
| "dependency_failed";
interface RecoverableError {
kind: ToolFailureKind;
message: string;
retryable: boolean;
retryAfterMs?: number;
suggestedAction?: string;
}
MCP reports failures through two channels. Protocol errors are JSON-RPC errors for an unknown tool, invalid arguments, or a server fault. A tool that ran and failed (an API error, a rate limit, a broken business rule) returns a normal result with isError: true, so the model sees the message and can adjust its next call. The 2025-11-25 revision moves input validation errors into this second channel too. The failure kinds above stay inside the server and the orchestrator: they decide retries and do not replace isError.
Error Handler with Retry Logic#
A retry is safe only when repeating the call cannot change the outcome. A timeout does not prove that the tool did nothing: the deploy may have started, and the specification lets a server ignore a cancellation for a request that cannot be cancelled. The handler below therefore retries only calls marked idempotent, plus calls that the MCP endpoint rejected with an HTTP 429, which normally means the tool never ran. It also gives every attempt its own AbortSignal, so a timed-out call is cancelled instead of left running behind a Promise.race.
import { StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
interface RetryPolicy {
maxRetries: number;
backoffMs: number;
multiplier: number;
}
interface CallSafety {
// true only for tools you control that are idempotent, or for calls
// that carry an idempotency key the server deduplicates on
idempotent: boolean;
// The SDK arms its own per-request timeout (60 s by default), so the
// executor passes timeoutMs to callTool along with the signal
timeoutMs: number;
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
class MCPErrorHandler {
private retryPolicies = new Map<ToolFailureKind, RetryPolicy>([
["timeout", { maxRetries: 3, backoffMs: 1000, multiplier: 2 }],
["dependency_failed", { maxRetries: 5, backoffMs: 500, multiplier: 1.5 }],
["rate_limited", { maxRetries: 3, backoffMs: 5000, multiplier: 2 }],
]);
async executeWithRecovery<T>(
toolName: string,
executor: (signal: AbortSignal, timeoutMs: number) => Promise<T>,
safety: CallSafety
): Promise<T> {
let attempt = 0;
while (true) {
// A fresh signal per attempt. On timeout it aborts the in-flight call;
// the SDK then sends notifications/cancelled to the server.
const signal = AbortSignal.timeout(safety.timeoutMs);
try {
return await executor(signal, safety.timeoutMs);
} catch (error) {
const failure = this.classifyError(error, toolName);
attempt++;
console.warn(`Tool ${toolName} failed (attempt ${attempt}):`, {
kind: failure.kind,
message: failure.message,
retryable: failure.retryable,
});
// A 429 normally means the call was rejected before it ran. Any other failure
// of a non-idempotent tool may have taken effect, so do not repeat it.
const safeToRepeat = safety.idempotent || failure.kind === "rate_limited";
const policy = this.retryPolicies.get(failure.kind);
if (!failure.retryable || !safeToRepeat || !policy || attempt >= policy.maxRetries) {
throw this.createToolError(failure, toolName);
}
const backoff =
failure.retryAfterMs ?? policy.backoffMs * Math.pow(policy.multiplier, attempt - 1);
const jitter = Math.random() * 0.1 * backoff;
await sleep(backoff + jitter);
}
}
}
private classifyError(error: any, toolName: string): RecoverableError {
const timedOut =
error?.name === "TimeoutError" ||
(error instanceof McpError && error.code === ErrorCode.RequestTimeout);
if (timedOut) {
return {
kind: "timeout",
message: `Tool ${toolName} timed out`,
retryable: true,
suggestedAction: "Check service health or increase timeout",
};
}
// HTTP status of the MCP endpoint; StreamableHTTPError carries it in `code`
const status = error instanceof StreamableHTTPError ? error.code : undefined;
if (status === 429) {
return {
kind: "rate_limited",
message: `Tool ${toolName} rate limited`,
retryable: true,
};
}
if (status !== undefined && status >= 500) {
return {
kind: "dependency_failed",
message: `Tool ${toolName} backend error`,
retryable: true,
};
}
return {
kind: "execution_failed",
message: `Tool ${toolName} failed: ${error.message}`,
retryable: false,
};
}
private createToolError(failure: RecoverableError, toolName: string): Error {
return new Error(`${toolName}: ${failure.message}`, { cause: failure });
}
}
A tool that ran and failed does not throw: callTool returns its result with isError: true. The handler passes that result back without a retry, and the model reads it and decides the next call. The caller states what is safe. idempotentHint from your own server is a reasonable input; a hint from a server you do not control is not (see the warning in Pattern 1). On the server side, pass extra.signal into the deployment client so that a cancelled call stops before it reaches a point of no return.
const errorHandler = new MCPErrorHandler();
// deploy_service is not idempotent: a timeout surfaces as an error and is not repeated
const deployment = await errorHandler.executeWithRecovery(
"deploy_service",
(signal, timeoutMs) =>
client.callTool({ name: "deploy_service", arguments: args }, undefined, { signal, timeout: timeoutMs }),
{ idempotent: false, timeoutMs: 120000 }
);
To make deploy_service retryable, give each call an idempotency key, for example one derived from the workflow execution ID, and have the server return the existing deployment for a key it has already seen. The idempotency guide covers the storage side of that pattern.
Circuit Breaker Pattern#
class CircuitBreaker {
private state: "closed" | "open" | "half-open" = "closed";
private failures = 0;
private lastFailureTime = 0;
constructor(
private readonly threshold: number = 5,
private readonly resetTimeout: number = 30000
) {}
async execute<T>(operation: () => Promise<T>): Promise<T> {
if (this.state === "open") {
if (Date.now() - this.lastFailureTime > this.resetTimeout) {
this.state = "half-open";
} else {
throw new Error("Circuit breaker is open");
}
}
try {
const result = await operation();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
private onSuccess(): void {
this.failures = 0;
this.state = "closed";
}
private onFailure(): void {
this.failures++;
this.lastFailureTime = Date.now();
if (this.failures >= this.threshold) {
this.state = "open";
console.log(`Circuit breaker opened after ${this.failures} failures`);
}
}
}
Pattern 6: Observability Stack#
Production MCP deployments need comprehensive observability across metrics, tracing, and audit logging.
import { trace, SpanStatusCode } from "@opentelemetry/api";
import { Counter, Histogram, Gauge } from "prom-client";
class MCPObservability {
private tracer = trace.getTracer("mcp-server");
// Prometheus metrics
private requestCounter = new Counter({
name: "mcp_tool_requests_total",
help: "Total MCP tool invocations",
labelNames: ["tool", "status", "user_role"],
});
private requestDuration = new Histogram({
name: "mcp_tool_duration_seconds",
help: "MCP tool execution duration",
labelNames: ["tool"],
buckets: [0.1, 0.5, 1, 2, 5, 10, 30],
});
private activeRequests = new Gauge({
name: "mcp_active_requests",
help: "Currently executing MCP requests",
});
async observedToolExecution<T>(
toolName: string,
user: User,
params: Record<string, any>,
executor: () => Promise<T>
): Promise<T> {
return this.tracer.startActiveSpan(`tool:${toolName}`, async (span) => {
const startTime = Date.now();
this.activeRequests.inc();
try {
span.setAttributes({
"mcp.tool.name": toolName,
"mcp.user.id": user.id,
"mcp.user.role": user.roles.join(","),
"mcp.params": JSON.stringify(this.sanitizeParams(params)),
});
const result = await executor();
span.setStatus({ code: SpanStatusCode.OK });
this.requestCounter.inc({
tool: toolName,
status: "success",
user_role: user.roles[0],
});
return result;
} catch (error) {
span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
span.recordException(error);
this.requestCounter.inc({
tool: toolName,
status: "error",
user_role: user.roles[0],
});
throw error;
} finally {
const duration = (Date.now() - startTime) / 1000;
this.requestDuration.observe({ tool: toolName }, duration);
this.activeRequests.dec();
span.end();
}
});
}
private sanitizeParams(params: Record<string, any>): Record<string, any> {
const sensitiveKeys = ["password", "token", "secret", "apiKey"];
const sanitized = { ...params };
for (const key of Object.keys(sanitized)) {
if (sensitiveKeys.some(s => key.toLowerCase().includes(s))) {
sanitized[key] = "[REDACTED]";
}
}
return sanitized;
}
}
Audit Logging for Compliance#
Audit events split into two paths. Security-critical events (a denial, an invocation of a gated tool, a scope change) go through record: the caller awaits an append to an append-only sink before the tool runs, so a crash cannot drop the record of a production deploy, and a sink outage fails the call closed. Routine events, such as a completed read, go through the batched log, where a crash loses at most one flush interval.
interface AuditEvent {
timestamp: string;
eventId: string;
userId: string;
userRoles: string[];
action: string;
resource: string;
params: unknown;
result: "started" | "success" | "failure" | "denied";
serverVersion: string;
environment: string;
}
type AuditInput = {
action: string;
user: User;
resource: string;
result: AuditEvent["result"];
params?: Record<string, unknown>;
};
// Append-only store: accepts new events, offers no update or delete
interface AuditSink {
append(events: AuditEvent[]): Promise<void>;
}
const SENSITIVE_KEYS = ["password", "token", "secret", "apikey", "authorization"];
// Recursive, so a token nested inside an argument object is caught too
export function redact(value: unknown): unknown {
if (Array.isArray(value)) return value.map(redact);
if (value !== null && typeof value === "object") {
return Object.fromEntries(
Object.entries(value).map(([key, inner]) => [
key,
SENSITIVE_KEYS.some((s) => key.toLowerCase().includes(s)) ? "[REDACTED]" : redact(inner),
])
);
}
return value;
}
export class AuditLogger {
private buffer: AuditEvent[] = [];
constructor(private sink: AuditSink, private config: AuditConfig) {
// Routine events flush every 10 seconds
setInterval(() => void this.flush(), 10000).unref();
}
// Security-critical events: the caller awaits the write and
// does not run the tool until the event is durable
async record(event: AuditInput): Promise<void> {
await this.sink.append([this.toEvent(event)]);
}
// Routine events: batched; a crash loses at most one flush interval
log(event: AuditInput): void {
this.buffer.push(this.toEvent(event));
}
// The only path into an AuditEvent, so every event is redacted
private toEvent(event: AuditInput): AuditEvent {
return {
timestamp: new Date().toISOString(),
eventId: crypto.randomUUID(),
userId: event.user.id,
userRoles: event.user.roles,
action: event.action,
resource: event.resource,
params: redact(event.params ?? {}),
result: event.result,
serverVersion: this.config.serverVersion,
environment: this.config.environment,
};
}
private async flush(): Promise<void> {
if (this.buffer.length === 0) return;
const batch = this.buffer;
this.buffer = [];
try {
await this.sink.append(batch);
} catch (error) {
console.error("Audit flush failed:", error);
this.buffer.unshift(...batch); // Re-queue failed events
}
}
}
toEvent is the only place an AuditEvent is built, so redaction cannot be skipped by a caller that forgets it. The SecureMCPServer in Pattern 3 passes raw arguments and relies on this.
Implementation Order#
Six patterns at once is a lot to absorb. The order below keeps the first version shippable while leaving room for the rest.
Start with identity, then gate the tools that change production. Validate bearer tokens before the first tool ships, and take the user from the validated token. In the same release, put the RBAC check and a write-ahead audit record in front of every tool that can change production state. Read-only tools can run on authentication alone until a second team needs different access.
Get one workflow working end-to-end before abstracting. The temptation is to build a general-purpose orchestrator. Resist it. Pick your most critical multi-step operation and hardcode the workflow. Only extract patterns once you have two or three working workflows to compare.
Instrument the first server before it has users. Metrics and tracing are cheap to add up front and awkward to backfill. When authorization issues arise (and they will), the traces show which tool call was denied and for which role, instead of leaving you to reconstruct that from client-side symptoms.
Progressive authorization is worth the complexity. Starting users with minimal scopes and elevating on demand feels like more work than granting broad permissions upfront. But the security posture and audit clarity it provides justify the investment. Add it right after RBAC, while the list of sensitive tools in the scope map is still short.
Circuit breakers prevent cascading failures. If your MCP servers call external services (databases, APIs, other services), wrap those calls in circuit breakers immediately. One slow dependency can bring down your entire agent system without them.
Each pattern answers one scaling problem, so adopt it when that problem shows up in your own system. A server that validates tokens and gates its production tools is ready to ship, and fine-grained roles for read-only tools can follow.
Common Pitfalls#
Over-Permissioning#
Granting broad permissions to avoid authorization errors during development creates security debt. Start minimal, add incrementally based on actual needs.
Monolithic Tools#
Creating large tools that do everything makes them harder to secure, test, and compose. Design small, focused tools that chain together.
Ignoring Partial Failures#
Assuming workflows either fully succeed or fully fail leads to inconsistent states. Track workflow state, implement compensation actions, and support resumption from failure points.
Context Window Blindness#
Returning excessive data from tools wastes context window capacity. Return only relevant data, use structured output schemas, and implement progressive loading for large results.
Security as Afterthought#
Adding security after initial implementation leads to architectural rework. Put token validation in front of the first tool, and put RBAC and audit in front of every tool that can change production from its first release.
When These Patterns Pay Off#
All six patterns assume that more than one team touches the same MCP servers. A single-team server with three read-only tools needs none of this: a token check and structured logs cover it, and role inheritance or scope elevation would only add moving parts. The line is crossed when a second consumer arrives with different permissions, or when any registered tool can change production state. At that point RBAC and audit logging come first, because fitting a permission model onto tools that agents already call means touching every caller. Orchestration, retries, and circuit breakers can follow one workflow at a time.
References#
- Model Context Protocol Specification (opens in new tab) - Official MCP specification defining the protocol requirements and transport details
- MCP Tools (2025-06-18) (opens in new tab) - Tool annotations as untrusted hints, and the split between protocol errors and
isErrortool results - MCP Authorization (2025-11-25) (opens in new tab) - OAuth 2.1 with PKCE, token audience validation, and the
insufficient_scopestep-up flow - MCP Key Changes in 2025-11-25 (opens in new tab) - What the revision after 2025-06-18 added, including incremental scope consent
- MCP Cancellation (2025-06-18) (opens in new tab) - How
notifications/cancelledworks and when a server may ignore it - MCP TypeScript SDK (opens in new tab) - Reference implementation for MCP servers and clients, including
registerTool,requireBearerAuth,StreamableHTTPError, and per-request timeouts (60 s by default) - OpenTelemetry JavaScript Documentation (opens in new tab) - Distributed tracing and observability instrumentation for Node.js
- OpenTelemetry Specification (opens in new tab) - Vendor-neutral specification for traces, metrics, and logs
- OWASP Authorization Cheat Sheet (opens in new tab) - Security best practices for RBAC implementation
- JSON-RPC 2.0 Specification (opens in new tab) - Protocol foundation for MCP error codes and transport
- Circuit Breaker Pattern (opens in new tab) - Martin Fowler’s explanation of the resilience pattern
Related posts
How Zapier MCP narrows AI agent API access to whitelisted actions, locked fields, and one revocable credential, and where a custom scoped proxy still wins.
mcp · security · ai-agents +4
Build SaaS authorization with AWS Cognito and Verified Permissions, covering Cedar policies, multi-tenant patterns, JWT flow, and cost in TypeScript.
authorization · aws · authentication +4
A vendor-neutral evaluation of AWS Verified Permissions, Cedar, OpenFGA, SpiceDB, Cerbos, and OPA: deployment, consistency, cost drivers, and a decision tree.
authorization · security · architecture +4
A deep comparison of Cedar, Rego, OpenFGA DSL, and Cerbos YAML/CEL policy languages: syntax, performance, formal verification, tooling, and TypeScript integration.
authorization · security · architecture +2
SpiceDB vs Auth0 FGA (OpenFGA): when ZedTokens, self-hosting or AuthZed's managed SpiceDB beat the default, plus list queries, outbox sync and pricing.
authorization · security · architecture +3