TypeScript Usage Guide

This guide covers how the MCPWatch TypeScript SDK instruments your MCP server and what gets captured.

Instrumenting your server

The instrument() function is the primary API. It wraps your server’s registration and lifecycle methods to automatically capture events:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { instrument } from "@mcpwatch/sdk";

const server = instrument(
  new McpServer({ name: "my-server", version: "1.0.0" }),
  {
    apiKey: process.env.MCPWATCH_API_KEY ?? "",
    endpoint: "https://api.mcpwatch.dev",
    debug: true,
  }
);

After instrumenting, define tools, resources, and prompts as you normally would:

server.tool("search_files", { query: { type: "string" } }, async (args) => {
  const results = await searchIndex(args.query);
  return { content: [{ type: "text", text: JSON.stringify(results) }] };
});

server.resource("config://app", "Application config", async () => {
  return { contents: [{ uri: "config://app", text: readConfig() }] };
});

server.prompt("summarize", { text: { type: "string" } }, async (args) => {
  return { messages: [{ role: "user", content: { type: "text", text: args.text } }] };
});

Each handler invocation is automatically captured as an event with timing, arguments, response, and error data.

What gets captured

The SDK wraps these server methods:

MethodEvent TypeCaptured Data
server.tool()tool_callTool name, arguments, result, duration, errors
server.resource()resource_readResource name, params, response, duration
server.prompt()prompt_getPrompt name, params, response, duration
server.connect()initializeTransport type, server name/version, client info
server.close()closeServer name, session duration
Notification methodsnotificationNotification type, params

Notification methods wrapped after connect(): sendLoggingMessage, sendResourceListChanged, sendToolListChanged, sendPromptListChanged, sendResourceUpdated.

Sampling

Control the percentage of events captured with the sampleRate option:

const server = instrument(
  new McpServer({ name: "my-server", version: "1.0.0" }),
  {
    apiKey: process.env.MCPWATCH_API_KEY ?? "",
    sampleRate: 0.1, // Capture 10% of events
  }
);

Sampling is applied per handler invocation. A sampleRate of 0.5 means each tool call has a 50% chance of being captured. Errors that occur within a sampled call are still captured.

Quota management

MCPWatch tracks your event quota and provides feedback through response headers. You can register a callback to be notified when your quota is running low:

const server = instrument(
  new McpServer({ name: "my-server", version: "1.0.0" }),
  {
    apiKey: process.env.MCPWATCH_API_KEY ?? "",
    onQuotaWarning: (info) => {
      console.warn(`Quota ${info.status}: ${info.remaining}/${info.limit} remaining, resets ${info.reset}`);
    },
  }
);

When your quota hits the hard limit (HTTP 429), the SDK automatically pauses ingestion and resumes after the Retry-After period. Events generated during the pause are dropped.

Transport detection

The SDK auto-detects your transport type when server.connect(transport) is called. Detected types:

  • stdioStdioServerTransport or objects with stdin/stdout properties
  • sseSSEServerTransport or objects with _endpoint/_url properties
  • streamable-httpStreamableHTTPServerTransport or objects with handleRequest
  • unknown — Fallback when no match is found

The transport type is included in every event for filtering in the dashboard.

Graceful shutdown

Call server.close() to ensure all pending events are flushed before your process exits:

await server.close();

The SDK also registers handlers for SIGINT, SIGTERM, and beforeExit to attempt a final flush on unexpected shutdowns.

Error handling

The SDK is designed to never interfere with your server’s operation:

  • If event delivery fails, it retries once after 1 second, then drops the event
  • If the event queue exceeds 1000 pending events, the oldest are dropped
  • Network errors are caught and logged (with debug: true) but never thrown
  • HTTP request timeout is 10 seconds

Next steps

Last updated — MCPWatch Documentation