Skip to main content

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​

FeatureDetails
Package@zihin/mcp-server
Tools96 (5 consumer + 3 consumer-profile + 4 consumer-ops + 44 builder-read + 40 builder-write)
Resources19 (agents, schema-templates, models + 10 formal contracts zihin://schemas/{type} + 6 skills zihin://skills/{slug})
Skills6 expert playbooks (create agent, tools, triggers, diagnostics, governance) — served by the server, installable natively per IDE
Guided Prompts3 (setup-agent, add-tool, configure-webhook)
Tool AnnotationsAll 96 tools ship MCP ToolAnnotations (read-only/destructive/idempotent/open-world hints + title)
Transportsstdio (via npm package) + HTTP Streamable (direct)
Server instructions

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

Fastest path — plugin (MCP server + the 6 skills in one command; requires ZIHIN_API_KEY exported in your shell):

claude plugin marketplace add zihin-ai/zihin-mcp
claude plugin install zihin@zihin

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​

VariableRequiredDescription
ZIHIN_API_KEYYesAPI Key for authentication
ZIHIN_MCP_URLNoOverride 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.

EndpointMethodDescription
/mcpPOSTInitialize session or process JSON-RPC request
/mcpGETSSE stream for server notifications
/mcpDELETEClose 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.

Required Headers

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.

HeaderFormatExample
X-Api-KeyDirectX-Api-Key: YOUR_API_KEY
AuthorizationBearer with zhn_ prefixAuthorization: Bearer YOUR_API_KEY
PrefixEnvironment
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.

RoleAvailable ToolsDescription
owner96 (all)Tenant owner — full access
admin96 (all)Full access: consumer + consumer-profile + consumer-ops + builder-read + builder-write. Default for new keys.
editor52 (consumer + consumer-profile + builder-read)Read access (own sessions, aggregated profiles, builder reads). Write operations and consumer-ops are not even listed.
member5 (consumer only)End-user access: identify session, list agents, chat, view sessions

Tool categories:

CategoryCountOperationsRoles
consumer5Identify session, list published agents, chat, sessionsowner, admin, editor, member
consumer-profile3Aggregated cross-consumer reads (get_consumer_profile, list_consumers, list_consumer_sessions)owner, admin, editor
consumer-ops4Tenant-wide mutations on consumers/sessions (deny, suspend, manual message, cancel turn)owner, admin only
builder-read44list_*, get_*, validate_*, compare_* + budget/approval reads + observabilityowner, admin, editor
builder-write40create_*, update_*, delete_*, toggle_*, publish_*, rollback_*, clone_*, test_*, set_agent_budgetowner, admin only
Enforcement

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.

Anti-escalation

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).

ToolDescription
whoamiIdentify the current session: tenant name, role, and subscription plan
list_published_agentsList published agents available for chat
chat_with_agentSend a message and receive a response (includes tool_calls, model_used, execution_time_ms). Integrations (admin/owner key) can also send consumer_key, context, bindings, session_from and metadata — see Agent invocation contract
list_agent_sessionsList recent sessions for an agent (filters: control_mode, consumer_key, roots_only to exclude sub-agent sessions)
get_session_historyGet 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.

ToolDescription
get_consumer_profileGet aggregated consumer profile (cross-session, cross-agent): display name, channels used, total sessions, total turns, agents interacted, product flags, timestamps
list_consumersPaginated 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_sessionsPaginated 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.

ToolDescription
set_consumer_denylistAdd or remove a consumer from the tenant-wide denylist. When active, all messages from that consumer are bypassed cross-agent (no LLM, no quota)
set_session_controlChange a session's control_mode (engaged, suspended, manual_handoff). When ≠ engaged, the agent loop is bypassed for new messages on that session
send_manual_messageSend a manual operator message through the same outbound channel as the agent (Twilio/Meta/webhook). Requires control_mode != engaged. Message is recorded as human-authored so the agent doesn't imitate the style if it resumes
cancel_agent_turnCancel an in-progress agent turn (mid-LLM, mid-tool, mid-stream). Useful for loop runaway, off-target responses, or compliance stops. In multi-agent (sub-agent) sessions, propagates via root_execution_id
Session Lifecycle

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)​

ToolCategoryDescription
list_agentsreadList tenant agents (filters: status, type, include_archived)
get_agentreadAgent details with schemas
create_agentwriteCreate agent (model format: provider.model, e.g. openai.gpt-4.1-nano, or auto for intelligent routing)
update_agentwriteUpdate agent metadata. Also accepts chat_enabled (boolean) to enable/disable the agent on the native chat channel (chat.zihin.ai)
delete_agentwriteArchive or hard-delete agent
clone_agentwriteClone agent with schemas and optionally triggers
publish_agentwritePublish agent (validates all schemas first)

Schemas (5 tools)​

ToolCategoryDescription
list_schemasreadList schemas for an agent (filters: schema_type, include_inactive)
get_schemareadSchema details
create_schemawriteCreate schema with integrated validation
update_schemawriteUpdate schema with re-validation
delete_schemawriteRemove schema

Schema types: persona_config, api_config, db_config, workflow_config, skill_config, mcp_tool_config, mcp_resource_config

Contract-first workflow (avoids trial and error)

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)​

ToolCategoryDescription
list_triggersreadList triggers (filters: agent_id, trigger_type, enabled)
get_triggerreadTrigger details
create_triggerwriteCreate trigger (webhook returns callable URL + API Key)
update_triggerwriteUpdate trigger configuration
delete_triggerwriteSoft delete
toggle_triggerwriteEnable/disable
list_trigger_executionsreadExecution history
get_trigger_executionreadExecution details
get_session_trigger_contextreadReverse lookup: given a session_id, returns the trigger and execution that originated the session

Trigger types: webhook, db_event, email, schedule


Connections (6 tools)​

ToolCategoryDescription
list_connectionsreadList database connections
get_connectionreadConnection details (secrets masked)
create_connectionwriteCreate connection (providers: postgresql, supabase)
update_connectionwriteUpdate configuration
delete_connectionwriteSoft delete
test_connectionwriteTest database connectivity

Connection Schema (3 tools)​

ToolCategoryDescription
get_connection_schemareadDatabase schema via cache (tables, columns, types)
get_connection_semanticreadSemantic context (domains, keywords, entities)
refresh_connection_schemawriteRe-introspect database and update cache

MCP Servers (7 tools)​

Manage external MCP servers connected to agents (not the Zihin MCP Server itself).

ToolCategoryDescription
list_mcp_serversreadList MCP servers for an agent
get_mcp_serverreadMCP server details
create_mcp_serverwriteRegister an external MCP server
update_mcp_serverwriteUpdate configuration
delete_mcp_serverwriteRemove MCP server from agent
test_mcp_serverwriteTest connectivity to an MCP server endpoint (ping + latency)
invalidate_mcp_cachewriteClear cached tools (force reload)

API Keys (5 tools)​

ToolCategoryDescription
list_api_keysreadList tenant API Keys (includes revoked)
get_api_keyreadGet details of a specific API Key
create_api_keywriteCreate API Key with role (anti-escalation enforced)
update_api_keywriteUpdate RPM of an existing API Key
delete_api_keywriteRevoke API Key permanently

Security Policies — CSP (7 tools)​

ToolCategoryDescription
list_cspsreadList security policies
get_cspreadPolicy details
create_cspwriteCreate policy (types: schedule, behavior, data, origin, custom)
update_cspwriteUpdate policy
delete_cspwriteSoft delete
toggle_cspwriteActivate/deactivate
get_effective_cspsreadMerged effective policies for an agent

Scopes (hierarchical): tenant > team > agent > user


Secrets (4 tools)​

ToolCategoryDescription
list_secretsreadList secrets (values never exposed)
create_secretwriteCreate encrypted secret (AES-256-GCM)
update_secretwriteUpdate secret value
delete_secretwriteSoft delete
caution

The plaintext value is shown only once at creation time. Store it immediately.


Introspection and Validation (7 tools)​

ToolCategoryDescription
get_agent_fullreadComplete agent view (schemas + triggers + CSPs)
list_agent_toolsreadAll resolved tools (api_config + db_config + MCP + core), with resolved/error status
validate_agent_schemasreadValidate all schemas for an agent
toggle_schemawriteActivate/deactivate a schema
test_triggerwriteSimulate trigger execution with test payload
validate_schema_datareadDry-run: validate schema data without saving — same server-side JSON Schema validation as create_schema/update_schema. Supports all canonical types, including trigger_config and csp_config
get_agent_metricsreadExecution metrics by period (1d, 7d, 30d): LLM calls, errors, success rate, tokens, cost, p50/p95 latency (aggregated server-side — 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.

ToolCategoryDescription
get_agent_budgetreadCurrent cycle balance and effective cap for an agent (unlimited: true = no cap set)
list_agent_budgetsreadBalance/cap of all tenant agents in one batch call
set_agent_budgetwriteSet 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.

ToolCategoryDescription
list_approvalsreadPending approval requests for the tenant. admin/owner see all; editor is scoped to own requests + what they can approve
list_approval_policiesreadApproval policies (filter active_only)
get_approval_policyreadPolicy details (name, stages, approvers, is_active)
create_approval_policywriteCreate a policy. stages[].approvers accepts {type:"user", id} or {type:"role", role}
update_approval_policywriteUpdate 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 server-side — no row caps.

ToolCategoryDescription
get_agent_lineagereadOrchestrator→sub-agent pairs that actually invoked each other (via invoke_agent), with invocation counts — complements allowed_invoke_agents (which is "may invoke")
get_tenant_healthreadTenant-level infra errors not attributable to a specific agent (provider auth, rate limit), grouped by canonical error code
get_execution_tracereadHierarchical multi-agent execution trace from a root_execution_id: supervisor→sub-agents with phases, tool calls and cost per node
get_session_agent_treereadAgent 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)​

ToolCategoryDescription
list_versionsreadVersion history for a resource
get_versionreadSpecific version details
compare_versionsreadDiff between two versions
rollback_versionwriteRestore resource to a previous version
list_snapshotsreadPublication snapshots for an agent
get_snapshotreadSnapshot details
rollback_snapshotwriteRestore full agent to a publication snapshot
list_agent_historyreadTimeline 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)​

ToolCategoryDescription
list_agent_memoryreadList persistent memory entries for an agent
delete_agent_memorywriteDelete a specific memory entry
get_scheduler_statusreadStatus of active scheduled triggers (cron jobs)

Resources​

Read-only data the AI assistant can reference:

URIDescription
zihin://agentsAll agents for the tenant with status, type, tags, and schema types
zihin://schema-templatesReady-to-use examples for each schema type (fields, examples, notes)
zihin://modelsAvailable 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. 10 types: api_config, persona_config, db_config, skill_config, workflow_config, mcp_tool_config, mcp_resource_config, trigger_config, csp_config, approval_policy
zihin://skills/{slug}Expert playbooks (6) — see Skills below

Each zihin://schemas/{type} resource also carries an mcp_usage field explaining granularity — critical to avoid contract errors:

  • schema_data types (api_config, persona_config, db_config, skill_config, workflow_config, mcp_*): the schema validates exactly the schema_data argument of create_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, the trigger_config argument of create_trigger corresponds to properties.trigger_config inside the contract.

Skills​

Six procedural playbooks that make the AI assistant a Zihin specialist. Unlike tool descriptions (what each tool does) and formal contracts (payload structure), skills encode multi-tool workflows, decision trees and the gotchas that cause silent failures — e.g. endpoint.name must equal tool_definition.name, or derive session strategy silently creating new sessions when context_mapping doesn't resolve.

SkillCovers
zihin://skills/mcpRouter: category map, RBAC, contract-first workflow, which skill to read next
zihin://skills/criar-agenteFull agent creation: create → persona (canonical format) → validate → publish
zihin://skills/tools-de-agenteAPI/SQL/external-MCP tools + the silent-failure rules
zihin://skills/triggers-e-canaisWebhook/schedule/email, session strategy, response formats per channel
zihin://skills/diagnostico7-step debugging decision tree + known failure signatures
zihin://skills/governanca-e-operacaoBudget, CSPs, HITL approvals, human handoff, denylist

Zero-install: every MCP client already receives the skills as resources — the server's instructions tell the model to read the relevant skill before multi-step flows.

Native install (context-triggered activation): install the skills in your IDE's native format:

# Claude Code (Agent Skills) | Cursor (rules) | Windsurf (rules) | Codex (AGENTS.md index)
ZIHIN_API_KEY=YOUR_API_KEY npx @zihin/mcp-server install-skills --client claude
ZIHIN_API_KEY=YOUR_API_KEY npx @zihin/mcp-server install-skills --client all

Options: --client claude|cursor|windsurf|codex|all · --dir <project-root> · --global (claude only, installs to ~/.claude/skills) · --bundled (offline, uses the copies shipped in the npm package). Skills are fetched from the live server by default — always current.

For Claude Code, the plugin installs the MCP server and the skills together.


Tool Annotations​

Every tool ships MCP ToolAnnotations, which clients use to calibrate their permission UX:

HintMeaning in Zihin
readOnlyHintReads only — safe to auto-approve. All list_*/get_*/validate_*/compare_* tools. Note: chat_with_agent is not read-only (it executes the agent)
destructiveHintdelete_*, rollback_* and cancel_agent_turn — clients should ask for confirmation
idempotentHintupdate_*, set_*, publish_agent, invalidate_mcp_cache — repeating with the same arguments has no additional effect
openWorldHintTools 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:

PromptArgumentsDescription
setup-agentname, type (assistant, chatbot, workflow, classifier)Complete wizard: create agent, configure persona, add tools, publish, optionally set up webhook
add-toolagent_id, tool_type (api_config, db_config)Guide to add a tool with validation rules (endpoint naming, path params, auth setup)
configure-webhookagent_idSet 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:

  1. Provide a name and type (e.g., data_analyst)
  2. 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:

  1. Select a connection from list_connections
  2. Explore the schema with get_connection_schema
  3. Define the query template with parameter placeholders ($1, $2)
  4. 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​

SettingValue
MCP servers per agent10 (max)
MCP tool cache5-minute TTL
Health check interval60 seconds
Tool call timeout30 seconds
Connection timeout10 seconds
Secrets encryptionAES-256-GCM
Session TTL by planfree: 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
}
CodeDescription
MISSING_API_KEYX-Api-Key header missing
INVALID_API_KEYAPI Key invalid or revoked
WRITE_BLOCKEDWrite operation blocked by RBAC (editor/member role)
ROLE_ESCALATION_DENIEDCannot create API Key with role higher than caller
NOT_FOUNDResource not found or does not belong to tenant
VALIDATION_ERRORInvalid data (schema_data, parameters)
MODEL_TIER_RESTRICTEDModel 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