Skip to main content
The shared types module (@mcp-ts/sdk/shared) provides the core TypeScript types used across server-side and client-side code. Import from @mcp-ts/sdk/server or @mcp-ts/sdk/client — both re-export everything from the shared module.

McpConnectionState

A string union representing the lifecycle of a single MCP connection. Both the server and the client use these states to communicate progress, errors, and readiness.
import type { McpConnectionState } from '@mcp-ts/sdk/server';

type McpConnectionState =
  | 'INITIALIZING'    // Session or connection setup is starting
  | 'VALIDATING'      // Checking an existing session's health
  | 'CONNECTING'      // Establishing the transport connection
  | 'CONNECTED'       // Transport connected; not yet ready for tool calls
  | 'DISCOVERING'     // Fetching tools, prompts, and resources from the server
  | 'READY'           // Fully connected; tools are available
  | 'AUTHENTICATING'  // OAuth flow is in progress
  | 'RECONNECTING'    // Reconnect attempt after an interruption
  | 'FAILED'          // A connection or auth error occurred
  | 'DISCONNECTED';   // Not connected; cleaned up
StateWhen it occurs
INITIALIZINGMCPClient.connect() is called for the first time; loading config from storage
VALIDATINGRestoring a session — verifying the server is still reachable
CONNECTINGOAuth tokens validated; transport handshake in progress
CONNECTEDTransport handshake succeeded; tool discovery about to start
DISCOVERINGlistTools() (or listPrompts, listResources) is running
READYTools discovered; the connection is usable
AUTHENTICATINGOAuth redirect issued; waiting for the user to authorize
RECONNECTINGBackground reconnect triggered after a transient failure
FAILEDNon-recoverable error; the connection must be removed or retried manually
DISCONNECTEDdisconnect() was called or the transport closed cleanly

McpConnectionEvent

A discriminated union emitted by MCPClient and forwarded over SSE to connected browser clients. Subscribe via onConnectionEvent in useMcp.
import type { McpConnectionEvent } from '@mcp-ts/sdk/server';
type McpConnectionEvent =
  | {
      type: 'state_changed';
      sessionId: string;
      serverId: string;
      serverName: string;
      serverUrl: string;
      state: McpConnectionState;
      previousState: McpConnectionState;
      createdAt?: number;
      timestamp: number;
    }
  | {
      type: 'tools_discovered';
      sessionId: string;
      serverId: string;
      toolCount: number;
      tools: Tool[];
      timestamp: number;
    }
  | {
      type: 'auth_required';
      sessionId: string;
      serverId: string;
      authUrl: string;
      timestamp: number;
    }
  | {
      type: 'error';
      sessionId: string;
      serverId: string;
      error: string;
      errorType: 'connection' | 'auth' | 'validation' | 'unknown';
      timestamp: number;
    }
  | {
      type: 'disconnected';
      sessionId: string;
      serverId: string;
      reason?: string;
      timestamp: number;
    }
  | {
      type: 'progress';
      sessionId: string;
      serverId: string;
      message: string;
      timestamp: number;
    };
Fired whenever the connection state transitions. previousState lets you implement fine-grained UI updates.
mcp.useMcp({
  url: '/api/mcp',
  identity: userId,
  onConnectionEvent(event) {
    if (event.type === 'state_changed' && event.state === 'READY') {
      console.log(`${event.serverName} is ready with session ${event.sessionId}`);
    }
  },
});
Fired after listTools() succeeds. Contains the full tool list. The useMcp hook automatically updates the connections[].tools array when this event arrives.
Fired when the server returns a 401 and an OAuth URL is available. The useMcp hook redirects to authUrl automatically (or calls onRedirect if provided).
Fired when a connection, auth, or validation step fails. The errorType field narrows the cause.
Fired when a session is cleanly closed. The useMcp hook removes the connection from connections on this event.
Informational messages emitted during long-running steps (e.g. "Validating OAuth tokens...", "Connected successfully").

McpObservabilityEvent

Structured log events emitted alongside connection events. Use these for debugging, tracing, or shipping logs to an observability backend.
import type { McpObservabilityEvent } from '@mcp-ts/sdk/server';

interface McpObservabilityEvent {
  type?: string;          // e.g. 'mcp:client:state_change', 'mcp:client:tool_call'
  level?: 'debug' | 'info' | 'warn' | 'error';
  message?: string;       // Machine-readable message
  displayMessage?: string; // Human-readable message
  sessionId?: string;
  serverId?: string;
  payload?: Record<string, any>;
  metadata?: Record<string, any>;
  timestamp: number;
  id?: string;
}
Receive these via the onLog callback in useMcp:
useMcp({
  url: '/api/mcp',
  identity: userId,
  onLog(level, message, metadata) {
    if (level === 'error') {
      Sentry.captureMessage(message, { extra: metadata });
    }
  },
});

ToolInfo

A lightweight representation of a tool. Used in connections[].tools on the client side.
import type { ToolInfo } from '@mcp-ts/sdk/server';

type ToolInfo = {
  name: string;
  description?: string;
  inputSchema?: unknown;
};
For the full MCP SDK Tool type (including inputSchema.properties and required), use:
import type { Tool } from '@mcp-ts/sdk/server';
// Tool is re-exported from @modelcontextprotocol/sdk/types

SessionInfo

A lightweight session summary returned by getSessions(). Does not include OAuth tokens.
interface SessionInfo {
  sessionId: string;
  serverUrl: string;
  transport: 'sse' | 'streamable_http';
  createdAt: number;
  serverId?: string;
  serverName?: string;
  /**
   * false = auth is pending and the session should not be auto-restored.
   * undefined = legacy record; treated as active for backwards compatibility.
   */
  active?: boolean;
}

ConnectRequest / ConnectResponse

RPC types used when connecting to an MCP server via the SSE client.
interface ConnectRequest {
  serverUrl: string;
  callbackUrl: string;
}

type ConnectResponse =
  | { success: true; sessionId: string }
  | { requiresAuth: true; authUrl: string; sessionId: string }
  | { error: string };
Use the type guards to narrow the response:
import { isConnectSuccess, isConnectAuthRequired, isConnectError } from '@mcp-ts/sdk/server';

if (isConnectSuccess(response)) {
  console.log('Session ID:', response.sessionId);
} else if (isConnectAuthRequired(response)) {
  window.location.href = response.authUrl;
} else if (isConnectError(response)) {
  console.error(response.error);
}

CallToolRequest / CallToolResponse

RPC types for tool execution.
interface CallToolRequest {
  sessionId: string;
  toolName: string;
  toolArgs: Record<string, unknown>;
}

type CallToolResponse =
  | {
      content: Array<{ type: string; text?: string; [key: string]: unknown }>;
      isError: boolean;
    }
  | { error: string };

ListToolsResponse

RPC response type for listing tools.
type ListToolsResponse =
  | { tools: Tool[] }
  | { error: string };
Use the isListToolsSuccess type guard:
import { isListToolsSuccess } from '@mcp-ts/sdk/server';

const response = await client.listTools();
if (isListToolsSuccess(response)) {
  console.log(response.tools.map(t => t.name));
}

UnauthorizedError

Thrown by MCPClient.connect() when the server requires OAuth authorization and a valid authUrl is available.
import { UnauthorizedError } from '@mcp-ts/sdk/server';

try {
  await client.connect();
} catch (error) {
  if (error instanceof UnauthorizedError) {
    // The client has already emitted 'auth_required' with the URL.
    // In server-side usage with MCPClient directly, redirect here:
    res.redirect(oauthProvider.authUrl);
  }
}
The error message is 'OAuth authorization required'. The authUrl is not a property of UnauthorizedError itself — it is emitted via the auth_required connection event on the client’s onConnectionEvent emitter.

Utility classes

Emitter<T>

A type-safe event emitter for connection and observability events. Used by MCPClient and SSEClient, and exported for advanced use cases.
import { Emitter } from '@mcp-ts/sdk/server';

const emitter = new Emitter<{ message: string }>();

const disposable = emitter.event((event) => {
  console.log(event.message);
});

emitter.fire({ message: 'hello' });
disposable.dispose(); // unsubscribe

DisposableStore

Collects multiple Disposable objects and disposes them all at once. Useful in useEffect cleanup.
import { DisposableStore } from '@mcp-ts/sdk/client';

const store = new DisposableStore();
store.add(emitter.event(handler));
store.add(otherEmitter.event(otherHandler));

// cleanup:
store.dispose();