# MCP Server Integration and Tool Exposure to Agents in Paperclip AI: Implementation Guide

> Integrate MCP servers with Paperclip AI agents. Our secure Tool Gateway exposes JSON-RPC 2.0 endpoints for session management and tool discovery. Learn more!

- Repository: [Paperclip/paperclip](https://github.com/paperclipai/paperclip)
- Tags: how-to-guide
- Published: 2026-08-12

---

**Paperclip AI exposes external MCP servers to agents through a secure Tool Gateway subsystem that provides JSON-RPC 2.0 endpoints for session management, tool discovery, and controlled invocation with built-in approval workflows for destructive operations.**

Paperclip AI enables autonomous agents to safely invoke external services via the Managed Control Plane (MCP) protocol. The `paperclipai/paperclip` repository implements this integration through a centralized **ToolGatewayService** that handles authentication, rate limiting, and policy enforcement while exposing a uniform API for tool discovery and execution.

## Core Architecture Components

The MCP integration layer consists of several coordinated components that manage the lifecycle of tool sessions and executions.

### ToolGatewayService

The [[`server/src/services/tool-gateway.ts`](https://github.com/paperclipai/paperclip/blob/main/server/src/services/tool-gateway.ts)](https://github.com/paperclipai/paperclip/blob/master/server/src/services/tool-gateway.ts) file contains the core business logic for all MCP-related operations. This service implements **session creation**, **token validation**, **tool discovery**, **call execution**, and **approval workflows**. It manages four configurable rate-limit buckets (authentication failures, gateway requests, token requests, and session setup) and writes comprehensive audit events to `toolAccessAuditEvents`.

### Express Routes and HTTP Interface

The [[`server/src/routes/tool-gateway.ts`](https://github.com/paperclipai/paperclip/blob/main/server/src/routes/tool-gateway.ts)](https://github.com/paperclipai/paperclip/blob/master/server/src/routes/tool-gateway.ts) file exposes the service via HTTP endpoints. Key routes include:

- `POST /tool-gateway/sessions` – Creates authenticated sessions
- `GET /tool-gateway/tools` – Returns merged tool listings
- `POST /tool-gateway/tools/call` – Executes tool invocations
- `POST /tool-gateway/action-requests/:id/approve` – Handles human approvals

### Tool Categories

The gateway exposes three distinct tool categories:

- **Built-in MCP fixtures** – Demo tools like `mcp-remote-fixture:echo` defined in `BUILTIN_TOOLS`
- **Virtual tools** – Gateway helpers such as `search_tools` and `run_tool` that operate on the gateway itself rather than remote servers
- **Connected MCP tools** – Live connections to external services, namespaced as `mcp.<connection-namespace>:<tool-slug>`

## Session Management and Authentication

Agent access to MCP tools requires authenticated sessions secured via bearer tokens.

### Session Creation and Token Format

When an agent requests a session via `POST /tool-gateway/sessions`, the service creates a session row and generates a bearer token with the prefix `pcgt_` (format: `pcgt_<id>.<random>`). The token hash is stored in the database while the plain token returns to the client. Sessions support optional time-to-live (TTL) configuration and can be restricted to specific gateway IDs.

### Token Validation

Subsequent requests must include the `x-paperclip-tool-gateway-token` header. The service validates tokens using `getActiveSession` and `hashGatewayToken`, verifying the session exists, is not revoked, and has not expired.

## Tool Discovery and Classification

The gateway provides a unified interface for discovering available tools across multiple providers.

### Tool Naming Convention

MCP tools follow a strict namespacing scheme: `mcp.<connection-namespace>:<tool-slug>`. The namespace derives from the application key or connection name combined with a short stable ID, ensuring uniqueness across companies. The `connectedMcpToolsForCompany` function builds these gateway tool names from active **Tool Connections** (`mcp_remote` or `local_stdio`).

### Risk Inference and Policy Enforcement

The gateway automatically classifies tools by risk level using the `inferToolRisk` function:

- **Destructive** – Names containing `delete` or `remove`
- **Write** – Names containing `create`, `update`, or `write`
- **Read** – All other operations

This classification drives the **human-in-the-loop** approval system. The `toolAccessPolicyService` checks agent-profile bindings to determine authorization before execution.

## Executing Tool Calls

Tool invocation follows a JSON-RPC 2.0 protocol with varying workflows based on risk classification.

### Read-Only Tool Execution

For **read** and **write** risk tools, agents call `POST /tool-gateway/tools/call` with a JSON-RPC request body:

```typescript
const result = await fetch(`${API_URL}${session.callUrl}`, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "x-paperclip-tool-gateway-token": session.token,
  },
  body: JSON.stringify({
    jsonrpc: "2.0",
    id: "req-1",
    method: "tools/call",
    params: {
      tool: "mcp-remote-fixture:echo",
      arguments: { message: "hello world" },
    },
  }),
}).then(r => r.json());

```

The service validates the token, checks policies, applies rate limits via `consumeProtocolRateLimit`, and forwards the request using `mcpHttpRequestHeaders` and `parseMcpHttpResponseBody`.

### Destructive Operations and Approval Workflows

When `toolRequiresFormalApproval` detects a **destructive** risk level (line 998), the call enters a parked state:

```typescript
const resp = await fetch(`${API_URL}${session.callUrl}`, { /* ... */ });
if (resp.status === 202) {
  const { actionRequestId } = await resp.json();
  // Human approval required
  await fetch(`${API_URL}/api/tool-gateway/action-requests/${actionRequestId}/approve`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-paperclip-tool-gateway-token": session.token,
    },
    body: JSON.stringify({ companyId }),
  });
}

```

The service creates an `actionRequestId`, posts an activity card, and awaits the `POST /tool-gateway/action-requests/:id/approve` route (line 517) before executing the tool.

## Security Controls and Rate Limiting

The gateway implements multiple defense-in-depth mechanisms to ensure safe agent operation.

### Rate Limiting and Protocol Limits

Four configurable counters stored in `toolGatewayRateLimitCounters` protect against abuse:

- **authFailures** – Tracks authentication attempts
- **gatewayRequests** – General API calls (default: 300 per minute)
- **tokenRequests** – Token generation attempts
- **sessionSetup** – New session creation

The `consumeProtocolRateLimit` and `pruneExpiredProtocolRateLimitCounters` functions manage these limits with automatic TTL expiration.

### Signed Arguments and Tamper Protection

When a `toolGatewayToken` includes a signing secret, the service protects against argument tampering using `signToolArguments` and `verifyToolArgumentsSignature`. This ensures agents cannot modify tool parameters after the policy check.

### Header Security Policy

Sensitive headers (Authorization, cookies, API keys) are filtered via `isSensitivePassthroughHeader` and `safeHeaderValue`. The gateway forwards only safe, static, or metadata headers to upstream MCP servers.

## Practical Implementation Examples

### Creating a Session

Agents initiate access by creating a session with optional TTL and gateway restrictions:

```typescript
const resp = await fetch(`${API_URL}/api/tool-gateway/sessions`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    companyId: "c_123",
    agentId: "a_456",
    ttlMs: 300_000,
  }),
});
const session = await resp.json();
// Returns: { sessionId, token, toolsUrl, callUrl }

```

*Implementation*: `createToolGatewayService(...).createSession` (called from the route at line 387 of [`tool-gateway.ts`](https://github.com/paperclipai/paperclip/blob/main/tool-gateway.ts)).

### Listing Available Tools

Retrieve the merged catalog of built-in, plugin, and connected MCP tools:

```typescript
const tools = await fetch(`${API_URL}${session.toolsUrl}?companyId=${companyId}`, {
  headers: { "x-paperclip-tool-gateway-token": session.token },
}).then(r => r.json());

```

*Implementation*: `allTools()` combines `BUILTIN_TOOLS` with plugin tools and `connectedMcpToolsForCompany`.

### Revoking Access

Sessions can be terminated immediately via the revoke endpoint:

```typescript
await fetch(`${API_URL}/api/tool-gateway/sessions/${session.sessionId}/revoke`, {
  method: "POST",
  headers: { 
    "Content-Type": "application/json", 
    "x-paperclip-tool-gateway-token": session.token 
  },
  body: JSON.stringify({ companyId }),
});

```

This marks the session as revoked in the database and writes a `tool_gateway.session_revoked` audit event.

## Summary

- **ToolGatewayService** in [`server/src/services/tool-gateway.ts`](https://github.com/paperclipai/paperclip/blob/main/server/src/services/tool-gateway.ts) provides the core MCP integration logic for session management, tool discovery, and execution.
- **Session tokens** use the `pcgt_` prefix with hashed storage and support TTL-based expiration and revocation.
- **Tool namespacing** follows the pattern `mcp.<namespace>:<tool-slug>` to ensure uniqueness across company boundaries.
- **Risk-based classification** automatically categorizes tools as read, write, or destructive, triggering human approval workflows for destructive operations.
- **Security controls** include configurable rate limiting, signed arguments to prevent tampering, and header filtering to protect sensitive credentials.
- **Audit logging** captures every session creation, tool call, and approval decision in `toolAccessAuditEvents`.

## Frequently Asked Questions

### What is the MCP protocol in Paperclip AI?

The Managed Control Plane (MCP) protocol in Paperclip AI is a standardized interface that allows agents to discover and invoke external tools through a secure gateway. According to the `paperclipai/paperclip` source code, the implementation uses JSON-RPC 2.0 for communication and supports both HTTP-based remote connections and local stdio processes, with built-in session management and policy enforcement.

### How does Paperclip AI handle destructive tool operations?

When the `inferToolRisk` function detects a tool name containing keywords like `delete` or `remove`, it classifies the operation as **destructive**. The `toolRequiresFormalApproval` check (line 998 in [`tool-gateway.ts`](https://github.com/paperclipai/paperclip/blob/main/tool-gateway.ts)) parks the call and creates an action request ID. The system then posts an approval card to the UI, requiring explicit human approval via `POST /tool-gateway/action-requests/:id/approve` before executing the tool.

### What authentication method does the Tool Gateway use?

The Tool Gateway uses **bearer token authentication** via the `x-paperclip-tool-gateway-token` header. Tokens follow the format `pcgt_<id>.<random>` and are hashed before storage. The service validates tokens against active sessions using `getActiveSession` and supports named gateway tokens with the `pcgw_` prefix for specific integration scenarios.

### How are rate limits enforced for MCP tool calls?

Rate limits are enforced through four configurable buckets stored in `toolGatewayRateLimitCounters`: authentication failures, gateway requests (defaulting to 300 per minute), token requests, and session setup. The `consumeProtocolRateLimit` function checks these counters before processing requests, while `pruneExpiredProtocolRateLimitCounters` automatically removes expired entries to maintain performance.