npm package: @mycloudclaw/mcp-sdk
Description: Lightweight MCP (Model Context Protocol) client SDK for CloudClaw agent endpoints
Author: CloudClaw
Latest version: 0.1.0

# @cloudclaw/mcp-sdk

A lightweight, **zero-dependency** MCP (Model Context Protocol) client SDK for
connecting to [CloudClaw](https://mycloudclaw.com) agent endpoints and any
MCP 2025-11-25 compliant server.

Works natively in **Node 18+**, **browsers**, and **Cloudflare Workers** — uses
only the standard Fetch API.

---

## Installation

```bash
npm install @cloudclaw/mcp-sdk
```

---

## Quick Start

```ts
import { createMcpClient } from '@cloudclaw/mcp-sdk';

// Connect and initialize in one step
const client = await createMcpClient({
  serverUri: 'https://my-agent.workers.dev/mcp',
  authType: 'bearer',
  authConfig: { token: 'my-secret-token' },
});

// List available tools
const tools = await client.listTools();
console.log(tools.map(t => t.name));

// Call a tool
const result = await client.callTool('search_web', {
  query: 'cloudflare workers mcp',
});

console.log(result.content[0].text);
```

---

## Authentication

### No auth

```ts
const client = new McpClient({
  serverUri: 'https://my-agent.workers.dev/mcp',
  // authType defaults to 'none'
});
```

### Bearer token

```ts
const client = new McpClient({
  serverUri: 'https://my-agent.workers.dev/mcp',
  authType: 'bearer',
  authConfig: { token: 'sk-my-secret-token' },
});
```

### API key header

```ts
const client = new McpClient({
  serverUri: 'https://my-agent.workers.dev/mcp',
  authType: 'api_key',
  authConfig: {
    header_name: 'X-API-Key',
    api_key: 'my-api-key',
  },
});
```

### OAuth2 access token

```ts
const client = new McpClient({
  serverUri: 'https://my-agent.workers.dev/mcp',
  authType: 'oauth2',
  authConfig: { access_token: 'ya29.xxx' },
});
```

---

## Tools

```ts
// List all tools
const tools = await client.listTools();
// [{ name, description, inputSchema }]

// Call a tool
const result = await client.callTool('tool_name', {
  param1: 'value1',
  param2: 42,
});

if (result.isError) {
  console.error('Tool returned an error:', result.content);
} else {
  for (const item of result.content) {
    if (item.type === 'text') {
      console.log(item.text);
    }
  }
}
```

---

## Resources

```ts
// List concrete resources
const resources = await client.listResources();

// List URI templates
const templates = await client.listResourceTemplates();

// Read a resource by URI
const { contents } = await client.readResource('file:///data/report.csv');
console.log(contents[0].text);
```

---

## Prompts

```ts
// List available prompt templates
const prompts = await client.listPrompts();

// Retrieve a rendered prompt
const { messages } = await client.getPrompt('summarize', {
  topic: 'Cloudflare Workers',
  length: 'short',
});
```

---

## Session Management

The `McpSessionManager` pools live client connections so the same server
connection is re-used across multiple callers within a process or Worker
isolate.

```ts
import { McpSessionManager } from '@cloudclaw/mcp-sdk';

const manager = new McpSessionManager({
  staleThresholdMs: 30 * 60 * 1000, // 30 min (default)
});

// Get or create a session
const session = await manager.getOrCreate('tenant-123:server-abc', {
  serverUri: 'https://my-agent.workers.dev/mcp',
  authType: 'bearer',
  authConfig: { token: 'my-token' },
});

if (session.status === 'connected') {
  const tools = await session.client.listTools();
}

// Evict idle sessions (call from a cron / setInterval)
const evicted = manager.cleanStaleSessions();
console.log(`Evicted ${evicted} stale sessions`);

// Close a specific session
manager.close('tenant-123:server-abc');
```

---

## Logging

Pass a custom logger to see internal request/response traces:

```ts
import { McpClient } from '@cloudclaw/mcp-sdk';

const client = new McpClient({
  serverUri: 'https://my-agent.workers.dev/mcp',
  logger: ({ level, message, data }) => {
    console[level](`[mcp] ${message}`, data ?? '');
  },
});
```

---

## Options Reference

```ts
interface McpClientOptions {
  /** Full URL of the MCP server endpoint (required). */
  serverUri: string;

  /** Transport: 'streamable-http' | 'sse'. Default: 'streamable-http'. */
  transport?: McpTransport;

  /** Auth strategy. Default: 'none'. */
  authType?: McpAuthType;

  /** Auth configuration (shape depends on authType). */
  authConfig?: McpAuthConfig;

  /** Request timeout in ms. Default: 30000. */
  timeoutMs?: number;

  /** MCP protocol version. Default: '2025-11-25'. */
  protocolVersion?: string;

  /** Name/version sent in the initialize handshake. */
  clientInfo?: { name: string; version: string };

  /** Optional structured logger callback. */
  logger?: McpLogger;
}
```

---

## Cloudflare Workers Example

```ts
// worker.ts
import { McpClient } from '@cloudclaw/mcp-sdk';

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const client = new McpClient({
      serverUri: env.MCP_SERVER_URI,
      authType: 'bearer',
      authConfig: { token: env.MCP_TOKEN },
    });

    const tools = await client.listTools();
    return Response.json({ tools });
  },
};
```

---

## Transport Support

| Transport         | Status   | Notes                                     |
|-------------------|----------|-------------------------------------------|
| streamable-http   | Stable   | HTTP POST, JSON-RPC 2.0                   |
| sse               | Stable   | Parses first `data:` event from SSE stream |

---

## Protocol Compliance

This SDK targets the **MCP 2025-11-25** specification:

- JSON-RPC 2.0 framing
- `initialize` / `notifications/initialized` handshake
- `Mcp-Session-Id` header for stateful sessions
- `tools/list`, `tools/call`
- `resources/list`, `resources/templates/list`, `resources/read`
- `prompts/list`, `prompts/get`

---

## License

MIT — Copyright (c) 2025 CloudClaw