MCP Server
The Zihin platform provides an MCP (Model Context Protocol) Server that lets you manage agents, schemas, triggers, connections, secrets, and more directly from AI-powered IDEs and tools.
Overview
| Feature | Details |
|---|---|
| Package | @zihin/mcp-server |
| Tools | 96 (5 consumer + 3 consumer-profile + 4 consumer-ops + 44 builder-read + 40 builder-write) |
| Resources | 13 (agents, schema-templates, models + 10 formal contracts zihin://schemas/{type}) |
| Guided Prompts | 3 (setup-agent, add-tool, configure-webhook) |
| Tool Annotations | All 96 tools ship MCP ToolAnnotations (read-only/destructive/idempotent/open-world hints + title) |
| Transports | stdio (via npm package) + HTTP Streamable (direct) |
On initialize, the server sends role-aware instructions describing the main workflows, critical rules (e.g. endpoint.name must equal tool_definition.name) and the recommended contract-first flow — your MCP client injects them into the model's context automatically.
Setup
Install nothing — use npx to run the MCP proxy directly.
Claude Desktop
Add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):
{
"mcpServers": {
"zihin": {
"command": "npx",
"args": ["-y", "@zihin/mcp-server"],
"env": {
"ZIHIN_API_KEY": "YOUR_API_KEY"
}
}
}
}
Claude Code
Add to your project's .mcp.json:
{
"mcpServers": {
"zihin": {
"command": "npx",
"args": ["-y", "@zihin/mcp-server"],
"env": {
"ZIHIN_API_KEY": "YOUR_API_KEY"
}
}
}
}
Or via CLI:
claude mcp add zihin -e ZIHIN_API_KEY=YOUR_API_KEY -- npx -y @zihin/mcp-server
Cursor
Add to .cursor/mcp.json in your project root or ~/.cursor/mcp.json globally:
{
"mcpServers": {
"zihin": {
"command": "npx",
"args": ["-y", "@zihin/mcp-server"],
"env": {
"ZIHIN_API_KEY": "YOUR_API_KEY"
}
}
}
}
Windsurf
Add to ~/.codeium/windsurf/mcp_config.json:
{
"mcpServers": {
"zihin": {
"command": "npx",
"args": ["-y", "@zihin/mcp-server"],
"env": {
"ZIHIN_API_KEY": "YOUR_API_KEY"
}
}
}
}
Codex (OpenAI)
Add to ~/.codex/config.toml or .codex/config.toml in your project:
[mcp_servers.zihin]
command = "npx"
args = ["-y", "@zihin/mcp-server"]
env_vars = ["ZIHIN_API_KEY"]
The ZIHIN_API_KEY variable must be set in your shell. Alternatively, to set it inline:
[mcp_servers.zihin]
command = "npx"
args = ["-y", "@zihin/mcp-server"]
[mcp_servers.zihin.env]
ZIHIN_API_KEY = "YOUR_API_KEY"
Other MCP Clients
Any MCP client that supports stdio transport can use the @zihin/mcp-server package. The pattern is the same: run npx -y @zihin/mcp-server with the ZIHIN_API_KEY environment variable set.
Environment Variables
| Variable | Required | Description |
|---|---|---|
ZIHIN_API_KEY | Yes | API Key for authentication |
ZIHIN_MCP_URL | No | Override the server URL (default: https://llm.zihin.ai/mcp) |
HTTP Transport
For programmatic or server-to-server access (e.g., N8N, Make, custom scripts), the MCP Server is available directly via HTTP — no npm package needed.
| Endpoint | Method | Description |
|---|---|---|
/mcp | POST | Initialize session or process JSON-RPC request |
/mcp | GET | SSE stream for server notifications |
/mcp | DELETE | Close session |
Responses are returned as text/event-stream (SSE). The mcp-session-id is returned in the response header of the initialize call — use it in all subsequent requests.
All HTTP transport requests must include the Accept: application/json, text/event-stream header. Without it, the server returns 406 Not Acceptable.
Initialize a session:
curl -X POST "https://llm.zihin.ai/mcp" \
-H "X-Api-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-03-26",
"capabilities": {},
"clientInfo": { "name": "my-app", "version": "1.0" }
}
}'
Call a tool:
curl -X POST "https://llm.zihin.ai/mcp" \
-H "X-Api-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-H "mcp-session-id: <session-id-from-initialize>" \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "list_agents",
"arguments": { "status": "published" }
}
}'
Authentication
The MCP Server uses the same API Key system as the REST API. See Authentication for details.
| Header | Format | Example |
|---|---|---|
X-Api-Key | Direct | X-Api-Key: YOUR_API_KEY |
Authorization | Bearer with zhn_ prefix | Authorization: Bearer YOUR_API_KEY |
| Prefix | Environment |
|---|---|
zhn_live_ | Production |
zhn_test_ | Testing |
zhn_dev_ | Development |
The API Key determines the tenant context. All operations are automatically scoped to the key's tenant.
Role-Based Access Control (RBAC)
Each API Key has a role that controls which tools are available. See API Keys - Role System for how to create keys with specific roles.
| Role | Available Tools | Description |
|---|---|---|
owner | 96 (all) | Tenant owner — full access |
admin | 96 (all) | Full access: consumer + consumer-profile + consumer-ops + builder-read + builder-write. Default for new keys. |
editor | 52 (consumer + consumer-profile + builder-read) | Read access (own sessions, aggregated profiles, builder reads). Write operations and consumer-ops are not even listed. |
member | 5 (consumer only) | End-user access: identify session, list agents, chat, view sessions |
Tool categories:
| Category | Count | Operations | Roles |
|---|---|---|---|
consumer | 5 | Identify session, list published agents, chat, sessions | owner, admin, editor, member |
consumer-profile | 3 | Aggregated cross-consumer reads (get_consumer_profile, list_consumers, list_consumer_sessions) | owner, admin, editor |
consumer-ops | 4 | Tenant-wide mutations on consumers/sessions (deny, suspend, manual message, cancel turn) | owner, admin only |
builder-read | 44 | list_*, get_*, validate_*, compare_* + budget/approval reads + observability | owner, admin, editor |
builder-write | 40 | create_*, update_*, delete_*, toggle_*, publish_*, rollback_*, clone_*, test_*, set_agent_budget | owner, admin only |
RBAC is enforced centrally at registration and at call time: (1) tools/list only exposes tools allowed for the key's role — an editor never sees write tools; (2) every write tool carries a server-side role guard evaluated on each call (covers keys downgraded mid-session). Both derive from a single category registry, so new tools are protected automatically.
The create_api_key tool enforces anti-escalation: you cannot create an API Key with a role higher than your own. For example, an editor cannot create an admin key.
Tools Reference
Consumer (5 tools)
Available to all roles (owner, admin, editor, member).
| Tool | Description |
|---|---|
whoami | Identify the current session: tenant name, role, and subscription plan |
list_published_agents | List published agents available for chat |
chat_with_agent | Send a message and receive a response (includes tool_calls, model_used, execution_time_ms) |
list_agent_sessions | List recent sessions for an agent (filters: control_mode, consumer_key, roots_only to exclude sub-agent sessions) |
get_session_history | Get message history for a session (user/assistant messages only) |
Example — chat_with_agent:
Tool: chat_with_agent
Arguments:
agent_id: "your-agent-uuid"
message: "List active contracts for this month"
session_id: "optional-session-id"
The response includes a session_id — pass it in subsequent calls to maintain conversation context.
Consumer Profile (3 tools)
Available to owner, admin, editor. Aggregated reads across consumers and sessions for the entire tenant.
| Tool | Description |
|---|---|
get_consumer_profile | Get aggregated consumer profile (cross-session, cross-agent): display name, channels used, total sessions, total turns, agents interacted, product flags, timestamps |
list_consumers | Paginated list of consumers, ordered by last_seen_at (desc). Filters: search (substring in display_name or consumer_key), blocked (true = only denylisted, false = only not-denylisted) |
list_consumer_sessions | Paginated list of a specific consumer's sessions (cross-agent, most recent first) — complements get_consumer_profile, which returns only aggregated counters |
Consumer Ops (4 tools)
Available to owner, admin only. Operational mutations that affect customer-facing behavior across the tenant.
| Tool | Description |
|---|---|
set_consumer_denylist | Add or remove a consumer from the tenant-wide denylist (flags.do_not_contact). When active, all messages from that consumer are bypassed cross-agent (no LLM, no quota) |
set_session_control | Change a session's control_mode (engaged, suspended, manual_handoff). When ≠ engaged, the agent loop is bypassed for new messages on that session |
send_manual_message | Send a manual operator message through the same outbound channel as the agent (Twilio/Meta/webhook). Requires control_mode != engaged. Message is stored with metadata.author='human' so the agent doesn't imitate the style if it resumes |
cancel_agent_turn | Cancel an in-progress agent turn (mid-LLM, mid-tool, mid-stream) via Redis pub/sub. Useful for loop runaway, off-target responses, or compliance stops. In multi-agent (sub-agent) sessions, propagates via root_execution_id |
These four tools work together: set_session_control(manual_handoff) then send_manual_message(...) is the typical handoff pattern. cancel_agent_turn is for the in-flight turn; set_session_control(suspended) blocks the next one.
Agents (7 tools)
| Tool | Category | Description |
|---|---|---|
list_agents | read | List tenant agents (filters: status, type, include_archived) |
get_agent | read | Agent details with schemas |
create_agent | write | Create agent (model format: provider.model, e.g. openai.gpt-4.1-nano, or auto for intelligent routing) |
update_agent | write | Update agent metadata. Also accepts chat_enabled (boolean) to enable/disable the agent on the native chat channel (chat.zihin.ai) |
delete_agent | write | Archive or hard-delete agent |
clone_agent | write | Clone agent with schemas and optionally triggers |
publish_agent | write | Publish agent (validates all schemas first) |
Schemas (5 tools)
| Tool | Category | Description |
|---|---|---|
list_schemas | read | List schemas for an agent (filters: schema_type, include_inactive) |
get_schema | read | Schema details |
create_schema | write | Create schema with integrated validation |
update_schema | write | Update schema with re-validation |
delete_schema | write | Remove schema |
Schema types: persona_config, api_config, db_config, workflow_config, skill_config, mcp_tool_config, mcp_resource_config
Each schema type has a formal contract exposed as a resource — zihin://schemas/{schema_type} — containing the exact JSON Schema the server validates with. Recommended flow: read the contract → build schema_data → dry-run with validate_schema_data → create_schema.
Triggers (9 tools)
| Tool | Category | Description |
|---|---|---|
list_triggers | read | List triggers (filters: agent_id, trigger_type, enabled) |
get_trigger | read | Trigger details |
create_trigger | write | Create trigger (webhook returns callable URL + API Key) |
update_trigger | write | Update trigger configuration |
delete_trigger | write | Soft delete |
toggle_trigger | write | Enable/disable |
list_trigger_executions | read | Execution history |
get_trigger_execution | read | Execution details |
get_session_trigger_context | read | Reverse lookup: given a session_id, returns the trigger and execution that originated the session |
Trigger types: webhook, db_event, email, schedule
Connections (6 tools)
| Tool | Category | Description |
|---|---|---|
list_connections | read | List database connections |
get_connection | read | Connection details (secrets masked) |
create_connection | write | Create connection (providers: postgresql, supabase) |
update_connection | write | Update configuration |
delete_connection | write | Soft delete |
test_connection | write | Test database connectivity |
Connection Schema (3 tools)
| Tool | Category | Description |
|---|---|---|
get_connection_schema | read | Database schema via cache (tables, columns, types) |
get_connection_semantic | read | Semantic context (domains, keywords, entities) |
refresh_connection_schema | write | Re-introspect database and update cache |
MCP Servers (7 tools)
Manage external MCP servers connected to agents (not the Zihin MCP Server itself).
| Tool | Category | Description |
|---|---|---|
list_mcp_servers | read | List MCP servers for an agent |
get_mcp_server | read | MCP server details |
create_mcp_server | write | Register an external MCP server |
update_mcp_server | write | Update configuration |
delete_mcp_server | write | Remove MCP server from agent |
test_mcp_server | write | Test connectivity to an MCP server endpoint (ping + latency) |
invalidate_mcp_cache | write | Clear cached tools (force reload) |
API Keys (5 tools)
| Tool | Category | Description |
|---|---|---|
list_api_keys | read | List tenant API Keys (includes revoked) |
get_api_key | read | Get details of a specific API Key |
create_api_key | write | Create API Key with role (anti-escalation enforced) |
update_api_key | write | Update RPM of an existing API Key |
delete_api_key | write | Revoke API Key permanently |
Security Policies — CSP (7 tools)
| Tool | Category | Description |
|---|---|---|
list_csps | read | List security policies |
get_csp | read | Policy details |
create_csp | write | Create policy (types: schedule, behavior, data, origin, custom) |
update_csp | write | Update policy |
delete_csp | write | Soft delete |
toggle_csp | write | Activate/deactivate |
get_effective_csps | read | Merged effective policies for an agent |
Scopes (hierarchical): tenant > team > agent > user
Secrets (4 tools)
| Tool | Category | Description |
|---|---|---|
list_secrets | read | List secrets (values never exposed) |
create_secret | write | Create encrypted secret (AES-256-GCM) |
update_secret | write | Update secret value |
delete_secret | write | Soft delete |
The plaintext value is shown only once at creation time. Store it immediately.
Introspection and Validation (7 tools)
| Tool | Category | Description |
|---|---|---|
get_agent_full | read | Complete agent view (schemas + triggers + CSPs) |
list_agent_tools | read | All resolved tools (api_config + db_config + MCP + core), with resolved/error status |
validate_agent_schemas | read | Validate all schemas for an agent |
toggle_schema | write | Activate/deactivate a schema |
test_trigger | write | Simulate trigger execution with test payload |
validate_schema_data | read | Dry-run: validate schema data without saving — same Ajv validation as create_schema/update_schema. Supports all canonical types, including trigger_config and csp_config |
get_agent_metrics | read | Execution metrics by period (1d, 7d, 30d): LLM calls, errors, success rate, tokens, cost, p50/p95 latency (aggregated in SQL — no row cap), tool usage (sampled, with sample_truncated disclosure) and sessions |
Budget (3 tools)
Per-agent spend cap in USD. Unlike the plan's token quota, the budget counts every LLM call — including BYOK.
| Tool | Category | Description |
|---|---|---|
get_agent_budget | read | Current cycle balance and effective cap for an agent (unlimited: true = no cap set) |
list_agent_budgets | read | Balance/cap of all tenant agents in one batch call |
set_agent_budget | write | Set or remove the cap (limit_usd: null = unlimited). Also the recovery loop: raising the cap lets a budget-stopped agent run again on the next turn |
Approvals — HITL (5 tools)
Human-in-the-loop approval governance: which tool calls require approval (configured per-scope on a CSP) and who approves them (approval policies). The approve/reject decision itself happens in the approver's native chat, not through this API.
| Tool | Category | Description |
|---|---|---|
list_approvals | read | Pending approval requests for the tenant. admin/owner see all; editor is scoped to own requests + what they can approve |
list_approval_policies | read | Approval policies (filter active_only) |
get_approval_policy | read | Policy details (name, stages, approvers, is_active) |
create_approval_policy | write | Create a policy. stages[].approvers accepts {type:"user", id} or {type:"role", role} |
update_approval_policy | write | Update name/description/stages or deactivate (is_active: false) |
To activate approval for an agent: create the policy, then link it on a CSP via behavior.approval_policy_id + behavior.require_approval_for (array of tool names or { source: "mcp"\|"api"\|"db" } matchers).
Observability (4 tools)
Aggregated in SQL — no PostgREST row caps.
| Tool | Category | Description |
|---|---|---|
get_agent_lineage | read | Orchestrator→sub-agent pairs that actually invoked each other (via invoke_agent), with invocation counts — complements allowed_invoke_agents (which is "may invoke") |
get_tenant_health | read | Tenant-level infra errors not attributable to a specific agent (provider auth, rate limit), grouped by canonical error code |
get_execution_trace | read | Hierarchical multi-agent execution trace from a root_execution_id: supervisor→sub-agents with phases, tool calls and cost per node |
get_session_agent_tree | read | Agent tree of a session (by parent-session lineage): supervisor + sub-agents across all turns — works where per-execution traces can't close the tree in multi-turn sessions |
Versioning (8 tools)
| Tool | Category | Description |
|---|---|---|
list_versions | read | Version history for a resource |
get_version | read | Specific version details |
compare_versions | read | Diff between two versions |
rollback_version | write | Restore resource to a previous version |
list_snapshots | read | Publication snapshots for an agent |
get_snapshot | read | Snapshot details |
rollback_snapshot | write | Restore full agent to a publication snapshot |
list_agent_history | read | Timeline of all changes to an agent |
Tracked resources: agent, schema, trigger, mcp_server
See Versioning for details on how per-resource history and publication snapshots work.
Memory and Scheduler (3 tools)
| Tool | Category | Description |
|---|---|---|
list_agent_memory | read | List persistent memory entries for an agent |
delete_agent_memory | write | Delete a specific memory entry |
get_scheduler_status | read | Status of active scheduled triggers (cron jobs) |
Resources
Read-only data the AI assistant can reference:
| URI | Description |
|---|---|
zihin://agents | All agents for the tenant with status, type, tags, and schema types |
zihin://schema-templates | Ready-to-use examples for each schema type (fields, examples, notes) |
zihin://models | Available LLM models with provider, pricing, capabilities, and context window |
zihin://schemas/{type} | Formal contract (JSON Schema) for each payload type — the exact schema the server validates with (Ajv). 10 types: api_config, persona_config, db_config, skill_config, workflow_config, mcp_tool_config, mcp_resource_config, trigger_config, csp_config, approval_policy |
Each zihin://schemas/{type} resource also carries an mcp_usage field explaining granularity — critical to avoid contract errors:
schema_datatypes (api_config,persona_config,db_config,skill_config,workflow_config,mcp_*): the schema validates exactly theschema_dataargument ofcreate_schema/update_schema/validate_schema_data.- Entity types (
trigger_config,csp_config,approval_policy): the schema validates the full record assembled server-side. You only send the tool's input fields —id,tenant_id, timestamps are injected by the server. For example, thetrigger_configargument ofcreate_triggercorresponds toproperties.trigger_configinside the contract.
Tool Annotations
Every tool ships MCP ToolAnnotations, which clients use to calibrate their permission UX:
| Hint | Meaning in Zihin |
|---|---|
readOnlyHint | Reads only — safe to auto-approve. All list_*/get_*/validate_*/compare_* tools. Note: chat_with_agent is not read-only (it executes the agent) |
destructiveHint | delete_*, rollback_* and cancel_agent_turn — clients should ask for confirmation |
idempotentHint | update_*, set_*, publish_agent, invalidate_mcp_cache — repeating with the same arguments has no additional effect |
openWorldHint | Tools that reach systems outside Zihin: chat_with_agent, test_trigger, test_connection, refresh_connection_schema, test_mcp_server, send_manual_message, invalidate_mcp_cache |
Guided Prompts
Step-by-step workflows the AI assistant can follow:
| Prompt | Arguments | Description |
|---|---|---|
setup-agent | name, type (assistant, chatbot, workflow, classifier) | Complete wizard: create agent, configure persona, add tools, publish, optionally set up webhook |
add-tool | agent_id, tool_type (api_config, db_config) | Guide to add a tool with validation rules (endpoint naming, path params, auth setup) |
configure-webhook | agent_id | Set up webhook trigger: query extraction, response format, session strategy, buffer/split config |
Usage Examples
Create an Agent with Guided Prompt
In Claude Desktop or Claude Code, select the setup-agent prompt:
- Provide a name and type (e.g.,
data_analyst) - The wizard guides you through:
- Defining the agent's persona and system prompt
- Selecting the LLM model and temperature
- Adding tools (database queries, APIs, or MCP servers)
- Publishing the agent
Add a Database Tool
Using the add-tool prompt with tool_type: db_config:
- Select a connection from
list_connections - Explore the schema with
get_connection_schema - Define the query template with parameter placeholders (
$1,$2) - Map parameters from the agent's input schema
Validate Before Publishing
Use introspection tools to verify your agent configuration:
1. get_agent_full → Review complete agent config
2. validate_agent_schemas → Check for errors in all schemas
3. list_agent_tools → See all resolved tools available at runtime
4. validate_schema_data → Dry-run validation for a specific schema
5. test_trigger → Execute a trigger with test payload
6. publish_agent → Publish when everything checks out
Limits and Configuration
| Setting | Value |
|---|---|
| MCP servers per agent | 10 (max) |
| MCP tool cache | 5-minute TTL |
| Health check interval | 60 seconds |
| Tool call timeout | 30 seconds |
| Connection timeout | 10 seconds |
| Secrets encryption | AES-256-GCM |
| Session TTL by plan | free: 24h, basic/pro: 7d, enterprise: 30d |
Error Handling
Tool errors return an object with isError: true:
{
"content": [
{
"type": "text",
"text": "{\"success\":false,\"error\":\"Agent not found\",\"code\":\"NOT_FOUND\"}"
}
],
"isError": true
}
| Code | Description |
|---|---|
MISSING_API_KEY | X-Api-Key header missing |
INVALID_API_KEY | API Key invalid or revoked |
WRITE_BLOCKED | Write operation blocked by RBAC (editor/member role) |
ROLE_ESCALATION_DENIED | Cannot create API Key with role higher than caller |
NOT_FOUND | Resource not found or does not belong to tenant |
VALIDATION_ERROR | Invalid data (schema_data, parameters) |
MODEL_TIER_RESTRICTED | Model tier not allowed for the tenant's plan |
Requirements
- Node.js >= 18
- Compatible with macOS, Linux, and Windows
Source Code
The @zihin/mcp-server package is open source: github.com/zihin-ai/zihin-mcp