> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aigmented.io/llms.txt
> Use this file to discover all available pages before exploring further.

# MCP Server

> Connect Aigmented to Claude Desktop, Cursor, and other MCP clients

The Aigmented MCP server lets you search, navigate, and pull content from your knowledge base directly inside Claude Desktop, Cursor, LibreChat, or any [MCP-compatible](https://modelcontextprotocol.io) client.

As of this release, the MCP server exposes the same data primitives that Aigmented's internal auto-wiki uses to build content — so your external agent (Claude, Cursor, etc.) can explore the knowledge graph, pull topic-scoped card sets, and synthesize its own documents, briefs, or training materials.

<Note>
  The MCP package `@aigmented/mcp` is not yet published to npm. For now, use the source build from the repository.
</Note>

## Setup for Claude Desktop

Add to your `claude_desktop_config.json`:

```json theme={null}
{
  "mcpServers": {
    "aigmented": {
      "command": "npx",
      "args": ["@aigmented/mcp"],
      "env": {
        "AIGMENTED_API_KEY": "sk-YOUR_API_KEY",
        "AIGMENTED_COLLECTION_ID": "49"
      }
    }
  }
}
```

## Setup for Cursor

Add to Cursor's MCP settings:

```json theme={null}
{
  "aigmented": {
    "command": "npx",
    "args": ["@aigmented/mcp"],
    "env": {
      "AIGMENTED_API_KEY": "sk-YOUR_API_KEY",
      "AIGMENTED_COLLECTION_ID": "49"
    }
  }
}
```

## Environment variables

| Variable                  | Required | Default                | Description                                               |
| ------------------------- | -------- | ---------------------- | --------------------------------------------------------- |
| `AIGMENTED_API_KEY`       | Yes      | —                      | Your API key (`sk-...`)                                   |
| `AIGMENTED_API_URL`       | No       | `https://aigmented.io` | API base URL                                              |
| `AIGMENTED_COLLECTION_ID` | No       | —                      | Default collection ID (if omitted, specify per-tool call) |

## Available tools

Thirteen tools are exposed by the MCP server, split into four groups.

### Discovery & Q\&A

#### `list_collections`

List all available knowledge collections. No parameters.

#### `search_knowledge`

Semantic search over the knowledge base.

| Parameter       | Required | Description                             |
| --------------- | -------- | --------------------------------------- |
| `query`         | Yes      | Search query                            |
| `collection_id` | No       | Collection ID (uses default if omitted) |
| `top_k`         | No       | Max results (default 5)                 |

#### `ask_question`

Ask a question and get an AI-generated answer with citations.

| Parameter       | Required | Description                             |
| --------------- | -------- | --------------------------------------- |
| `question`      | Yes      | Your question                           |
| `collection_id` | No       | Collection ID (uses default if omitted) |

#### `get_card_details`

Fetch full contents of a card with **complete source provenance**. Use this when you need to cite where information came from.

| Parameter | Required | Description                                |
| --------- | -------- | ------------------------------------------ |
| `card_id` | Yes      | Card ID (from search or retrieval results) |

Response includes:

* `card_id`, `title`, `statement`, `knowledge_type`, `importance_score`
* **`source_documents`** — array of `{id, name}` for every document the card was generated from
* **`page_numbers`** — flat array of all source page numbers (across all docs; the schema doesn't track per-doc page mapping)
* **`section_context`** — section path inside the source document (e.g. `"Chapter 3 / Vacations"`)
* **`related_header`** — nearest header in the source document
* **`verbatim_content`** — exact quote from the source, when applicable (forms, templates, legal text)
* **`source_card_ids`** — Phase 2 intermediate cards (deeper traceability)
* `related_card_ids` — up to 5 graph-derived neighbors (empty if no graph)
* `created_at`, `updated_at`

Also kept for backwards compatibility: `source_document` (the first entry of `source_documents` plus a `page_range` like `"12-14"`).

### Knowledge graph navigation

These tools require that the collection has a built knowledge graph. Collections without a graph will return a `409` error with a guiding message — use `retrieve_for_topic` or `search_knowledge` instead.

#### `describe_collection`

Returns collection statistics, graph-built flag, and a preview of top clusters. **Call this first** to understand what's available before running more expensive tools.

| Parameter       | Required | Description                             |
| --------------- | -------- | --------------------------------------- |
| `collection_id` | No       | Collection ID (uses default if omitted) |

Returns: `{ total_cards, has_graph, total_clusters, total_entities, top_clusters }`.

#### `list_clusters`

Lists all knowledge graph clusters (topics / communities) in a collection.

Each cluster contains: `id`, `llm_name`, `llm_description`, `card_count`, and up to 5 `top_entities`. Use this to get a structured view of "what topics exist in this collection".

#### `get_cluster`

Full detail of a single cluster: cards (with 200-character previews), entities, and related clusters.

| Parameter       | Required | Description                             |
| --------------- | -------- | --------------------------------------- |
| `cluster_id`    | Yes      | Cluster ID (from `list_clusters`)       |
| `collection_id` | No       | Collection ID (uses default if omitted) |

#### `list_entities`

Top entities (people, organizations, concepts) in the collection, with card counts.

| Parameter       | Required | Description                                       |
| --------------- | -------- | ------------------------------------------------- |
| `top_k`         | No       | Max results (default 50, max 200)                 |
| `entity_type`   | No       | Filter by type (e.g., `PERSON`, `ORG`, `CONCEPT`) |
| `collection_id` | No       | Collection ID (uses default if omitted)           |

#### `get_gaps`

Knowledge gaps: isolated entities (appearing in only one card with few relations) and undersized clusters. Useful for identifying coverage problems before generating content.

### Content retrieval

#### `retrieve_for_topic`

**The key tool for content creation.** Runs the same retrieval pipeline that Aigmented's auto-wiki uses internally: embedding search → importance filter → deduplication → Cohere reranking. Returns the most relevant cards for a given topic, ready to feed into your agent's synthesis step.

| Parameter        | Required | Description                                                        |
| ---------------- | -------- | ------------------------------------------------------------------ |
| `topic`          | Yes      | Topic or section title                                             |
| `description`    | No       | Longer description of what you're looking for (improves retrieval) |
| `top_k`          | No       | Max cards to return (default 25, max 50)                           |
| `rerank`         | No       | Run Cohere rerank (default `true`)                                 |
| `min_importance` | No       | Filter cards below this importance score (default `0.4`)           |
| `collection_id`  | No       | Collection ID (uses default if omitted)                            |

Returns cards as `{ card_id, title, statement, importance_score, knowledge_type }`.

### Card-level browsing

Use these when you want to enumerate, bulk-fetch, or explore semantic neighborhoods of individual cards — without going through the retrieval pipeline.

#### `list_collection_cards`

Flat paginated browse of all cards in a collection. No query needed. Useful for "show me what's in this collection" overviews.

| Parameter        | Required | Description                                           |
| ---------------- | -------- | ----------------------------------------------------- |
| `offset`         | No       | Pagination offset (default 0)                         |
| `limit`          | No       | Max cards per page (default 20, max 100)              |
| `knowledge_type` | No       | Filter by type (e.g. `fact`, `procedure`, `decision`) |
| `cluster_id`     | No       | Filter by graph cluster (requires built graph)        |
| `collection_id`  | No       | Collection ID (uses default if omitted)               |

Returns: `{ cards: [{card_id, title, statement, knowledge_type, importance_score}], total_count, offset, limit, has_more }`. Statement truncated to 200 chars — call `get_card_details` for full content.

#### `get_cards_batch`

Fetch full details of multiple cards in one call (up to 25 IDs). Use after `search_knowledge` / `retrieve_for_topic` when you need full content of several cards — avoids N round-trips.

| Parameter       | Required | Description                             |
| --------------- | -------- | --------------------------------------- |
| `card_ids`      | Yes      | Array of card IDs, length 1-25          |
| `collection_id` | No       | Collection ID (uses default if omitted) |

Returns: `{ cards: [...], not_found: [ids] }`.

#### `get_related_cards`

Find cards semantically similar to a given card. Use to build topical clusters around a single card (e.g. for quiz generation: "5 cards most related to card X").

| Parameter       | Required | Description                             |
| --------------- | -------- | --------------------------------------- |
| `card_id`       | Yes      | Source card ID                          |
| `limit`         | No       | Max related cards (default 5, max 20)   |
| `collection_id` | No       | Collection ID (uses default if omitted) |

Returns: `{ source_card_id, related: [{card_id, title, statement, similarity_score}] }`. Does not require a graph.

## Building content with MCP — a cookbook

The new tools let your agent replicate what Aigmented's auto-wiki does internally — navigating the graph and pulling topic-scoped sources — while keeping synthesis in your agent's hands. Some common patterns:

### 1. "Summarize what we know about X"

```
1. retrieve_for_topic(topic="X", top_k=20)
2. Agent reads the cards and writes a summary.
```

No graph needed. Works on any collection with search enabled.

### 2. "Generate a training section on onboarding"

```
1. describe_collection()               # confirm graph is built
2. list_clusters()                     # see all topics
3. get_cluster(cluster_id=<onboarding>)  # cards + entities in that cluster
4. retrieve_for_topic(topic="Onboarding for new hires", description="...", top_k=30)
5. Agent synthesizes using cards from steps 3 and 4 as source material.
```

### 3. "What people appear in our knowledge base?"

```
1. list_entities(entity_type="PERSON", top_k=100)
2. For each person of interest: retrieve_for_topic(topic=<person name>, top_k=10)
3. Agent builds a profile page per person.
```

### 4. "Where are our knowledge gaps?"

```
1. get_gaps()
2. Agent reports isolated entities and undersized topics — feeds back to a human reviewer or drives which documents to ingest next.
```

### 5. "Build a quiz around this specific card"

```
1. get_related_cards(card_id=<seed card>, limit=10)
2. get_cards_batch(card_ids=[...related IDs...])
3. Agent generates 5 questions + answers citing the source cards.
```

### 6. "Browse all cards in a collection and pick what's relevant"

```
1. describe_collection()                              # orient the agent
2. list_collection_cards(offset=0, limit=50)          # first page of lightweight summaries
3. list_collection_cards(offset=50, limit=50)         # continue
4. Agent picks IDs of interest → get_cards_batch([...])
```

This is the flow for an **admin building a learning program** — see what's available, cherry-pick sources, assemble content.

### Tips

* **Always start with `describe_collection`** on a fresh collection. It tells your agent whether graph tools are available and gives an at-a-glance map of topics.
* **Prefer `retrieve_for_topic` over `search_knowledge` for content generation** — it runs the fuller pipeline (importance filter + dedup + rerank) that produces cleaner source sets.
* **`get_card_details` is cheap** — once your agent has a card\_id from any other tool, pulling the full card is lightweight.
* **Cost note:** `retrieve_for_topic` uses Cohere embedding + reranking (paid). Default `top_k=25` is a good balance. Setting `rerank=false` skips the rerank if you're cost-sensitive.

## HTTP mode (LibreChat)

For LibreChat or other HTTP-based MCP clients, run the HTTP server:

```bash theme={null}
AIGMENTED_API_KEY=sk-YOUR_KEY npx @aigmented/mcp --http
```

This starts an HTTP server on port 3002 (configurable via `MCP_PORT`) with the MCP Streamable HTTP transport at `/mcp`.

## Errors and degradation

| Scenario                                   | What happens           | What to do                                                                                     |
| ------------------------------------------ | ---------------------- | ---------------------------------------------------------------------------------------------- |
| Collection has no graph built              | Graph tools return 409 | Use `retrieve_for_topic` / `search_knowledge` instead, or run `build-graphs` on the collection |
| `top_k > 50` on `retrieve_for_topic`       | 400 validation error   | Lower `top_k`                                                                                  |
| `limit > 100` on `list_collection_cards`   | 400                    | Lower `limit`                                                                                  |
| `card_ids > 25` on `get_cards_batch`       | 400                    | Split into multiple batches                                                                    |
| `get_related_cards` with missing `card_id` | 404                    | Verify the ID exists in the collection                                                         |
| Invalid / cross-team `collection_id`       | 404                    | Check the ID and that the API key belongs to the right team                                    |
| Token quota exceeded                       | 429                    | Wait for quota reset or request a higher limit                                                 |
