# Connect an AI Agent

URL: https://docs.clinia.com/docs/context-assembly/connect-an-ai-agent

> Configure an MCP client, give it access to a patient via the four VFS tools, and walk through a real clinical question end-to-end.

In this tutorial you will connect a language model to the Clinia Context Engine using the Model Context Protocol (MCP). By the end, the agent will be able to browse a patient's conditions, read a condition story, and answer a clinical question that requires traversing relationships across the graph.

**Time:** ~20 minutes.

## Prerequisites [#prerequisites]

- A patient already ingested. Complete [Ingest and Query a Patient](https://docs.clinia.com/docs/get-started/ingest-and-query-a-patient) first.
- Node.js 18+.
- An Anthropic API key and a Clinia Context Engine access token set in your environment:

```bash
export ANTHROPIC_API_KEY="your-anthropic-key"
export CLINIA_ACCESS_TOKEN="your-access-token"   # obtained via OAuth client credentials
```

See [Authentication and Credentials](https://docs.clinia.com/docs/platform/authentication-and-credentials) to obtain a Clinia Context Engine access token.

Replace `<workspace-id>` with your Clinia Context Engine workspace ID in the code below.

## Steps [#steps]

---

<Steps>
<Step>

### Install dependencies [#install-dependencies]

```bash
npm install @modelcontextprotocol/sdk @anthropic-ai/sdk
```

</Step>
<Step>

### Connect the MCP client [#connect-the-mcp-client]

The Clinia Context Engine exposes an MCP endpoint at `/mcp` over streamable HTTP. Connect to it and confirm the four tools are available:

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

const transport = new StreamableHTTPClientTransport(
  new URL("https://<workspace-id>.w.clinia.cloud/mcp"),
  {
    requestInit: {
      headers: { Authorization: `Bearer ${process.env.CLINIA_ACCESS_TOKEN}` },
    },
  },
);

const mcp = new Client({ name: "clinical-agent", version: "1.0.0" });
await mcp.connect(transport);

const { tools } = await mcp.listTools();
console.log(tools.map((t) => t.name));
// → ["browse_patient", "read_patient", "search_patient", "get_patient_info"]
```

Every tool takes the patient ID you chose as its `patient_id` argument, the same one as in the REST routes.

</Step>
<Step>

### Wire the tools to Claude [#wire-the-tools-to-claude]

Pass the MCP tools directly to the Anthropic SDK and let Claude decide when to call them:

```typescript
import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic();

const mcpTools = tools.map((t) => ({
  name: t.name,
  description: t.description ?? "",
  input_schema: t.inputSchema,
}));

async function runAgent(question: string): Promise<string> {
  const messages: Anthropic.MessageParam[] = [{ role: "user", content: question }];

  while (true) {
    const response = await anthropic.messages.create({
      model: "claude-sonnet-4-6",
      max_tokens: 4096,
      tools: mcpTools,
      messages,
    });

    if (response.stop_reason === "end_turn") {
      return response.content
        .filter((b) => b.type === "text")
        .map((b) => b.text)
        .join("");
    }

    const toolUses = response.content.filter((b) => b.type === "tool_use");
    if (toolUses.length === 0) break;

    const toolResults = await Promise.all(
      toolUses.map(async (use) => {
        if (use.type !== "tool_use") return null;
        const result = await mcp.callTool({
          name: use.name,
          arguments: use.input as Record<string, unknown>,
        });
        return {
          type: "tool_result" as const,
          tool_use_id: use.id,
          content: result.content
            .filter((c) => c.type === "text")
            .map((c) => c.text)
            .join("\n"),
        };
      }),
    );

    messages.push({ role: "assistant", content: response.content });
    messages.push({
      role: "user",
      content: toolResults.filter(Boolean) as Anthropic.ToolResultBlockParam[],
    });
  }

  return "";
}
```

</Step>
<Step>

### Run a clinical question [#run-a-clinical-question]

```typescript
const answer = await runAgent(
  "For patient jeanne-tremblay: given the recent acute COPD exacerbation, " +
    "is the current inhaler regimen appropriate and is bone health being monitored?",
);

console.log(answer);
await mcp.close();
```

The agent typically calls tools in this sequence:

1. `browse_patient` on `/patient/jeanne-72f-copd/conditions/active` to discover available conditions
2. `read_patient` on the `_story.md` of the entry displayed as chronic obstructive lung disease — the COPD story includes the acute exacerbation, current inhaler regimen, and spirometry trends
3. Optionally `read_patient` on the osteopenia entry's `_story.md` — surfaces the ICS exposure as a contributing factor and the pending DEXA follow-up
4. Synthesises the answer from the graph data

The agent reaches this conclusion without any application code that knows about ICS-related bone loss. It discovers the relationship from the condition stories, which were assembled by the pipeline from the clinical knowledge base.

</Step>
</Steps>

---

## Next steps [#next-steps]

- [MCP Server reference](https://docs.clinia.com/api/mcp/server) for full parameter documentation
- [Virtual File System](https://docs.clinia.com/docs/context-assembly/virtual-file-system) to understand the path schema your agent is navigating
- [Read a condition story](https://docs.clinia.com/docs/context-assembly/read-condition-story) for a focused how-to on format and token budget choices
