# MCP Integration Guide

## What is MCP?

**MCP (Model Context Protocol)** is a standard for connecting LLMs to external tools and APIs in a structured way. The Fiber MCP server exposes Fiber’s public API via:

- **Discovery tools** – list endpoints and inspect schemas.
- **Execution tools** – call specific operations with validated inputs.

This lets LLMs discover Fiber APIs, read instructions from `/llms.txt`, and then safely call operations like **company search**, **people search**, and **audience workflows**.

---

## Fiber MCP Server

The Fiber MCP server:

- Wraps the public `/v1/*` API (Fastify) using the OpenAPI specification.
- Is typically run as a **Docker image** and configured in your LLM client (e.g. Claude Desktop, Cursor, or another MCP host).
- Exposes tools that look like:
  - `search_endpoints` – canonical intent-based endpoint recommendation with ranked alternatives.
  - `get_endpoint_details_full` – returns the full schema for an operation (inputs/outputs).
  - `call_operation` – executes a specific operation (e.g. `companySearch`, `peopleSearch`, `createAudience`, `estimateEnrichmentCost`, `triggerEnrichment`, `exportCompanies`, `exportProspects`, etc.).

The exact tool names can be retrieved via the MCP host’s tool listing; use them as the single source of truth.

### Endpoint Surfaces

- `/mcp` – Core discovery & execution tools, API-key auth (default, backward compatible).
- `/mcp/v2` – Full generated-tool surface, API-key auth. Planned for deprecation after V3 rollout validation.
- `/mcp/lite` – Focused subset of search, lookup, instant contact lookup, typeahead, and reference-data tools, API-key auth.
- `/mcp/v3` – Full generated-tool surface, OAuth/SSO via Clerk. Recommended endpoint for agent integrations that want interactive login instead of API keys.

---

## Available Tools (Conceptual)

While names may vary slightly per deployment, the Fiber MCP integration generally exposes:

- **Discovery**
  - `search_endpoints` – recommend the best operations for an intent (supports optional constraints and ranked alternatives).
  - `get_endpoint_details_full` – inspect an endpoint’s parameters, request/response schemas, and pricing metadata.

- **Execution**
  - `call_operation` – run any operation by `operationId` using structured parameters.

Common `operationId` values include:

- `companySearch`
- `peopleSearch`
- `createAudience`
- `updateAudienceSearchParams`
- `buildAudience`
- `getAudienceStatus`
- `getEnrichmentStatus`
- `estimateEnrichmentCost`
- `triggerEnrichment`
- `exportCompanies`
- `exportProspects`
- Batch contact reveal operations:
  - `startBatchContactDetails`
  - `pollBatchContactDetails`

Refer to the OpenAPI spec at `/openapi.json` for the exact set and shapes.

---

## Best Practices for LLMs

### 1. Read `/llms.txt` First

Before using any tool:

- Fetch `/llms.txt` (served at the root) and load:
  - global rules (credits, confirmation, async polling),
  - the **Audience Workflow** overview,
  - links to detailed docs (this folder).
- Use these rules to guide all subsequent MCP calls:
  - **always** check credits before expensive operations,
  - **always** estimate and ask for confirmation,
  - **always** follow the audience workflow in order.

### 2. Discover, Then Call

When unsure which API to use:

1. Call `search_endpoints` with a human description (and constraints when available):
   - e.g. `"Need complete company profile by domain"` or `"find people by title"`.
2. If needed, call `list_all_endpoints` for broader discovery:
   - e.g. `"audience enrichment"`, `"batch contact enrichment"`, `"company search"`.
3. From the results, pick the most relevant `operationId`.
4. Call `get_endpoint_details_full` for that operation to see:
   - required fields (e.g. `apiKey`, `audienceId`),
   - optional filters,
   - rate limits and credit metadata.
5. Only then construct the `call_operation` payload.

This avoids guessing parameter shapes and prevents invalid requests.

### 2.1 Read API Selector Guidance

When you are choosing between similar operations (for example `companySearch` vs `kitchenSinkCompany`), read:

- [`/public/docs/api-selector.md`](/public/docs/api-selector.md)

This reduces wrong-tool calls and avoids unnecessary retries.

### 3. Use `call_operation` Safely

An example (conceptual) MCP payload for company search:

```json
{
  "operationId": "companySearch",
  "params": {
    "body": {
      "apiKey": "sk_live_xxx",
      "searchParams": {
        "keywords": ["artificial intelligence"],
        "headquartersCountryCode": ["US"]
      },
      "pageSize": 25,
      "cursor": null,
      "companyExclusionListIDs": []
    }
  }
}
```

General rules:

- Pass `apiKey` exactly where the schema expects it (body for `POST/PATCH/PUT`, query for `GET/DELETE`).
- Keep `searchParams` aligned with the returned schema from `get_endpoint_details_full`.
- Always check `chargeInfo` in responses and surface costs to the user.

---

## Recommended Workflows via MCP

### A. Audience-Based Enrichment (Recommended)

1. **Create audience**
   - `call_operation` with `operationId: "createAudience"`.
   - Store `audienceId`.
2. **Set search params**
   - `operationId: "updateAudienceSearchParams"`.
3. **Build audience**
   - `operationId: "buildAudience"`.
4. **Poll audience status**
   - `operationId: "getAudienceStatus"` until status is `NORMAL`.
5. **Estimate enrichment cost**
   - `operationId: "estimateEnrichmentCost"`.
   - Show `totalCredits` and `timeEstimate` to the user; ask for confirmation.
6. **Trigger enrichment**
   - `operationId: "triggerEnrichment"` (only after user confirms).
7. **Poll enrichment status**
   - `operationId: "getEnrichmentStatus"` until done.
8. **Export**
   - `operationId: "exportCompanies"` or `operationId: "exportProspects"` depending on user need.

This pattern is the most scalable for LLM agents because it:

- keeps large result sets in the database (not in context),
- provides clean async progress reporting,
- and makes cost transparent.

### B. Direct Search + Light Enrichment

1. Use `companySearch` or `peopleSearch` to fetch a **small page** (e.g. 25–50 results).
2. Summarize key fields in chat.
3. If user wants contact info for a few people:
   - call a **sync contact-enrich** endpoint per person.
4. If user wants to scale up:
   - propose creating an **audience** or **batch contact enrichment** job.

### C. Batch Contact Reveal via MCP

1. Start a batch:
   - `operationId: "startBatchContactDetails"`.
2. Poll:
   - `operationId: "pollBatchContactDetails"` with `taskId` and cursor.
3. Report:
   - use `overallStats` and `pageResults` to show progress and results.

---

## Cost and Safety Rules for MCP Agents

LLMs using MCP **must**:

- **Check credits** before large jobs:
  - Use `GET /v1/credits?apiKey=xxx` (or the equivalent MCP operation) and report the balance.
- **Estimate before charging**:
  - For audience enrichment, always call the estimate endpoint first.
- **Get explicit confirmation**:
  - Clearly state the estimated credits and time; ask:
    - “This will cost up to X credits and take about Y. Proceed?”
- **Poll instead of spamming**:
  - Respect documented poll intervals (e.g. every 30 seconds).
  - Avoid tight loops that abuse rate limits.

By combining `/llms.txt`, these docs, and the MCP tools, an LLM can reliably orchestrate complex Fiber workflows (search → audience → enrichment → export) while staying transparent and safe for end users.

