> For the complete documentation index, see [llms.txt](https://dnotifier.gitbook.io/product-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/mcp-server.md).

# Serve agents over MCP

Any agent or workflow you build with the SDK can also act as an **MCP server**. Once it is listening, MCP clients such as [Claude](https://claude.ai), [Cursor](https://cursor.com), and [VS Code](https://code.visualstudio.com) can discover it and call it through DNotifier — no extra server code, ports, or hosting on your side.

```
  MCP client (Claude, Cursor, your code)
         │  HTTPS + X-API-Key
         ▼
  DNotifier MCP endpoint
         │  realtime
         ▼
  Your process: agent.listen(notifier)
         │
         ▼
  Agent runs with your tools, keys, and data — reply goes back to the client
```

Your agent keeps running in your own process, with your own tools and credentials. DNotifier only routes requests to it and replies back to the caller.

## 1. Turn on the capability

Set `mcpServer: true` in the agent's or workflow's `capabilities`. Capabilities you leave out stay `false`.

{% tabs %}
{% tab title="JavaScript" %}

```js
const agent = DNotifier.defineAgent({
  name: "mermaid-diagram",
  description: "Generates Mermaid diagrams from a plain-language request.",
  instructions: "Write a Mermaid diagram for the user's request and validate it.",
  tools,
  capabilities: { mcpServer: true },
});

const workflow = new DNotifier.Workflow({
  name: "docs-pipeline",
  entry: async (ctx) => ctx.runAgent("mermaid-diagram", { input: ctx.input }),
  capabilities: { mcpServer: true },
}).registerAgents({ "mermaid-diagram": agent });
```

{% endtab %}

{% tab title="Python" %}

```python
agent = define_agent(
    name="mermaid-diagram",
    description="Generates Mermaid diagrams from a plain-language request.",
    instructions="Write a Mermaid diagram for the user's request and validate it.",
    tools=tools,
    capabilities={"mcpServer": True},
)

workflow = DNotifier.Workflow(
    name="docs-pipeline",
    entry=entry,
    capabilities={"mcpServer": True},
).register_agents({"mermaid-diagram": agent})
```

{% endtab %}

{% tab title="Dart" %}

```dart
final agent = defineAgent(
  name: 'mermaid-diagram',
  description: 'Generates Mermaid diagrams from a plain-language request.',
  instructions: "Write a Mermaid diagram for the user's request and validate it.",
  tools: tools,
  capabilities: {'mcpServer': true},
);

final workflow = Workflow(
  name: 'docs-pipeline',
  entry: entry,
  capabilities: {'mcpServer': true},
).registerAgents({'mermaid-diagram': agent});
```

{% endtab %}
{% endtabs %}

Give every agent a clear `description` — MCP clients show it to the model when deciding which tool to call.

## 2. Listen

Connect with **WebSocket** transport and call `listen`. Keep the process running: the agent is reachable only while the client is connected and listening. Call `stopListening` to take it offline.

{% tabs %}
{% tab title="JavaScript" %}

```js
import { DNotifier } from "@dnotifier-realtime/dnotifier";
import WebSocket from "ws";

const notifier = new DNotifier({
  appId: process.env.DNOTIFIER_APP_ID,
  secret: process.env.DNOTIFIER_SECRET,
  userId: "mermaid-host",
  transport: "ws",
  WebSocketImpl: WebSocket, // Node.js only
});

await notifier.connect();

agent.listen(notifier);       // a single agent
// workflow.listen(notifier); // or every agent on a workflow

// later
agent.stopListening();
// workflow.stopListening();
```

{% endtab %}

{% tab title="Python" %}

```python
notifier = DNotifier(
    app_id=os.environ["DNOTIFIER_APP_ID"],
    secret=os.environ["DNOTIFIER_SECRET"],
    user_id="mermaid-host",
    transport="ws",
)
await notifier.connect()

agent.listen(notifier)        # a single agent
# workflow.listen(notifier)   # or every agent on a workflow

# later
agent.stop_listening()
# workflow.stop_listening()
```

{% endtab %}

{% tab title="Dart" %}

```dart
final notifier = DNotifier(
  appId: Platform.environment['DNOTIFIER_APP_ID']!,
  secret: Platform.environment['DNOTIFIER_SECRET']!,
  userId: 'mermaid-host',
  transport: 'ws',
);
await notifier.connect();

agent.listen(notifier);       // a single agent
// workflow.listen(notifier); // or every agent on a workflow

// later
agent.stopListening();
// workflow.stopListening();
```

{% endtab %}
{% endtabs %}

Call `listen` once per agent you want to expose, or put several agents on one workflow and call `workflow.listen` once.

{% hint style="info" %}
For a long-running host, reconnect in `onDisconnected` and call `listen` again after each new connection.
{% endhint %}

### Sessions and checkpoints

MCP invokes can pass the same session / resume fields as `runAgent`: `sessionId`, `state`, `resume` / `mode`, and `fromCheckpointId`. The listening host resumes from that checkpoint (merging any provided `state`) instead of starting a one-off run.

→ [Checkpoints, sessions & resume](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/checkpoints.md)

## 3. Connect an MCP client

### Endpoint and key

| Deployment                            | MCP URL                                                             |
| ------------------------------------- | ------------------------------------------------------------------- |
| Shared DNotifier plan                 | `https://api.dnotifier.com/rpc/v1/mcp`                              |
| Enterprise on-premises / custom cloud | Provided with your deployment (may be an internal, protected route) |

Every request needs this header:

```
X-API-Key: <appId>:<userId>:<appSecret>
```

| Part        | Value                                                                                                                                                                        |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `appId`     | Your DNotifier app id                                                                                                                                                        |
| `userId`    | Any id that names the caller, for example `claude-desktop-alice` or `ci-bot`. Calls are grouped under this id in observability, so use a different one per client or person. |
| `appSecret` | Your DNotifier app secret                                                                                                                                                    |

{% hint style="warning" %}
The key contains your app secret. Keep it in environment variables or your client's secret storage, never in source control or shared config files.
{% endhint %}

In the examples below, set `DNOTIFIER_MCP_KEY` to the full `<appId>:<userId>:<appSecret>` value.

### Claude Code

[Claude Code](https://docs.anthropic.com/en/docs/claude-code/mcp) connects to remote MCP servers directly:

```bash
claude mcp add --transport http dnotifier https://api.dnotifier.com/rpc/v1/mcp \
  --header "X-API-Key: $DNOTIFIER_MCP_KEY"
```

### Claude Desktop

[Claude Desktop](https://claude.ai/download) can reach header-authenticated servers through the [`mcp-remote`](https://www.npmjs.com/package/mcp-remote) bridge. Add this to `claude_desktop_config.json` ([where to find it](https://modelcontextprotocol.io/quickstart/user)):

```json
{
  "mcpServers": {
    "dnotifier": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://api.dnotifier.com/rpc/v1/mcp",
        "--header",
        "X-API-Key:${DNOTIFIER_MCP_KEY}"
      ],
      "env": {
        "DNOTIFIER_MCP_KEY": "<appId>:<userId>:<appSecret>"
      }
    }
  }
}
```

Restart Claude Desktop after saving.

### Cursor

Add to `.cursor/mcp.json` in your project, or `~/.cursor/mcp.json` for all projects ([Cursor MCP docs](https://docs.cursor.com/context/model-context-protocol)):

```json
{
  "mcpServers": {
    "dnotifier": {
      "url": "https://api.dnotifier.com/rpc/v1/mcp",
      "headers": {
        "X-API-Key": "${env:DNOTIFIER_MCP_KEY}"
      }
    }
  }
}
```

### VS Code (GitHub Copilot)

Add to `.vscode/mcp.json` ([VS Code MCP docs](https://code.visualstudio.com/docs/copilot/chat/mcp-servers)). VS Code asks for the key once and stores it securely:

```json
{
  "inputs": [
    {
      "type": "promptString",
      "id": "dnotifier-key",
      "description": "DNotifier MCP key (<appId>:<userId>:<appSecret>)",
      "password": true
    }
  ],
  "servers": {
    "dnotifier": {
      "type": "http",
      "url": "https://api.dnotifier.com/rpc/v1/mcp",
      "headers": {
        "X-API-Key": "${input:dnotifier-key}"
      }
    }
  }
}
```

### MCP Inspector

To browse and test your agents by hand, run the [MCP Inspector](https://modelcontextprotocol.io/docs/tools/inspector):

```bash
npx @modelcontextprotocol/inspector
```

Choose **Streamable HTTP**, enter the MCP URL, and add the `X-API-Key` header.

### From code

{% tabs %}
{% tab title="DNotifier SDK" %}
Another DNotifier app can use your agents as tools in its own agents:

```js
const remote = await notifier.mcp.connect({
  id: "dnotifier-agents",
  name: "My DNotifier agents",
  transport: "http",
  endpoint: "https://api.dnotifier.com/rpc/v1/mcp",
  headers: { "X-API-Key": process.env.DNOTIFIER_MCP_KEY },
});

const orchestrator = DNotifier.defineAgent({
  name: "orchestrator",
  instructions: "Delegate diagram requests to the available tools.",
  tools: remote.tools(),
});
```

Python and Dart accept the same `headers` option on `notifier.mcp.connect`.
{% endtab %}

{% tab title="TypeScript MCP SDK" %}
Using the official [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk):

```ts
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";

const transport = new StreamableHTTPClientTransport(
  new URL("https://api.dnotifier.com/rpc/v1/mcp"),
  { requestInit: { headers: { "X-API-Key": process.env.DNOTIFIER_MCP_KEY! } } },
);

const client = new Client({ name: "my-app", version: "1.0.0" });
await client.connect(transport);

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

{% endtab %}

{% tab title="Python MCP SDK" %}
Using the official [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk):

```python
import asyncio
import os

from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client


async def main():
    async with streamablehttp_client(
        "https://api.dnotifier.com/rpc/v1/mcp",
        headers={"X-API-Key": os.environ["DNOTIFIER_MCP_KEY"]},
    ) as (read, write, _):
        async with ClientSession(read, write) as session:
            await session.initialize()
            tools = await session.list_tools()
            print([t.name for t in tools.tools])


asyncio.run(main())
```

{% endtab %}
{% endtabs %}

## Limits

| Limit        | Value                                          |
| ------------ | ---------------------------------------------- |
| Request body | 1 MB JSON                                      |
| Availability | Only while the host is connected and listening |

## Troubleshooting

| Symptom                | Check                                                                                                            |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------- |
| Client lists no agents | The agent or workflow has `capabilities: { mcpServer: true }`, and the host is connected and has called `listen` |
| `401` / `403`          | The `X-API-Key` format is `<appId>:<userId>:<appSecret>` and the app id and secret belong to the same app        |
| Call times out         | The host process is still running and connected over WebSocket (`transport: "ws"`)                               |
| Agent is not reachable | Its name matches exactly, and `stopListening` hasn't been called                                                 |

## Next steps

* [**Agent-to-agent (A2A)**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/a2a.md) — let other agents call yours over the A2A protocol
* [**Define an agent**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/define-agent.md) — all agent fields and capabilities
* [**Example: MCP Mermaid agent**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/example-mcp-agent.md) — build the agent used above
