# Admin API Source: https://docs.meshai.dev/api-reference/admin Platform-level tenant management (platform:admin scope required) These endpoints require the `platform:admin` scope. They are intended for MeshAI platform operators, not regular tenants. ## List Tenants ``` GET /admin/tenants ``` List all tenants on the platform. | Parameter | Type | Description | | --------- | ------- | -------------------------------------------------------------------------- | | `plan` | string | Filter by plan: `starter`, `professional`, `enterprise`, `enterprise_plus` | | `page` | integer | Page number | | `limit` | integer | Results per page | ```bash theme={null} curl https://api.meshai.dev/api/v1/admin/tenants \ -H "Authorization: Bearer msh_PLATFORM_ADMIN_KEY" ``` ```json Response theme={null} { "success": true, "data": [ { "id": "tnt_abc123", "company_name": "Acme Corp", "plan": "professional", "active_agents": 47, "agent_limit": 100, "owner_email": "admin@acme.com", "monthly_cost_usd": 799.00, "created_at": "2026-01-15T08:00:00Z", "last_activity": "2026-03-17T10:30:00Z" }, { "id": "tnt_def456", "company_name": "Globex Inc", "plan": "enterprise", "active_agents": 234, "agent_limit": 1000, "owner_email": "admin@globex.com", "monthly_cost_usd": 1999.00, "created_at": "2026-02-01T08:00:00Z", "last_activity": "2026-03-17T09:15:00Z" } ], "meta": { "total": 42, "page": 1, "limit": 20 } } ``` ## Create a Tenant ``` POST /admin/tenants ``` Provision a new tenant (e.g., for enterprise onboarding or testing). ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/admin/tenants \ -H "Authorization: Bearer msh_PLATFORM_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "company_name": "NewCo Ltd", "owner_email": "admin@newco.com", "plan": "enterprise", "agent_limit": 500 }' ``` ```json Response theme={null} { "success": true, "data": { "id": "tnt_ghi789", "company_name": "NewCo Ltd", "plan": "enterprise", "agent_limit": 500, "owner_email": "admin@newco.com", "api_key": "msh_live_newco_abc123", "created_at": "2026-03-17T10:00:00Z" } } ``` The API key is shown once at creation time. Share it securely with the tenant admin. ## Delete a Tenant ``` DELETE /admin/tenants/{tenant_id} ``` Permanently delete a tenant and all associated data (agents, policies, audit events, billing). ```bash theme={null} curl -X DELETE https://api.meshai.dev/api/v1/admin/tenants/tnt_abc123 \ -H "Authorization: Bearer msh_PLATFORM_ADMIN_KEY" ``` Returns `204 No Content` on success. This action is irreversible. All tenant data is permanently deleted. Use with extreme caution. # Agents API Source: https://docs.meshai.dev/api-reference/agents Register, list, update, and delete agents. Manage teams. ## List Agents ``` GET /agents ``` Query parameters: | Parameter | Type | Description | | ------------- | ------- | ------------------------------------------------ | | `status` | string | Filter: `healthy`, `degraded`, `down`, `unknown` | | `framework` | string | Filter by framework | | `team` | string | Filter by team | | `environment` | string | Filter: `production`, `staging`, `dev` | | `page` | integer | Page number (default: 1) | | `limit` | integer | Results per page (default: 20, max: 100) | ```bash theme={null} curl "https://api.meshai.dev/api/v1/agents?status=healthy&limit=50" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": [ { "id": "agt_abc123", "name": "production-summarizer", "description": "Summarizes customer support tickets", "framework": "crewai", "model_provider": "openai", "model_name": "gpt-4o", "environment": "production", "status": "healthy", "team": "support-team", "risk_level": "limited", "last_heartbeat": "2026-03-17T10:30:00Z", "created_at": "2026-03-01T08:00:00Z" } ], "meta": { "total": 12, "page": 1, "limit": 50 } } ``` ## Register an Agent ``` POST /agents ``` ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/agents \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "production-summarizer", "description": "Summarizes customer support tickets", "framework": "crewai", "model_provider": "openai", "model_name": "gpt-4o", "environment": "production", "team": "support-team", "tags": {"version": "1.2.0"} }' ``` ```json Response theme={null} { "success": true, "data": { "id": "agt_abc123", "name": "production-summarizer", "description": "Summarizes customer support tickets", "framework": "crewai", "model_provider": "openai", "model_name": "gpt-4o", "environment": "production", "status": "unknown", "team": "support-team", "tags": {"version": "1.2.0"}, "created_at": "2026-03-17T10:00:00Z" } } ``` ## Get an Agent ``` GET /agents/{agent_id} ``` ```bash theme={null} curl https://api.meshai.dev/api/v1/agents/agt_abc123 \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ## Update an Agent ``` PATCH /agents/{agent_id} ``` ```bash theme={null} curl -X PATCH https://api.meshai.dev/api/v1/agents/agt_abc123 \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "description": "Summarizes and categorizes support tickets", "model_name": "gpt-4o-mini", "tags": {"version": "1.3.0"} }' ``` ## Delete an Agent ``` DELETE /agents/{agent_id} ``` ```bash theme={null} curl -X DELETE https://api.meshai.dev/api/v1/agents/agt_abc123 \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` Returns `204 No Content` on success. The agent's historical data is preserved in the audit trail. ## Teams ### List Teams ``` GET /teams ``` ```bash theme={null} curl https://api.meshai.dev/api/v1/teams \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": [ { "id": "team_abc123", "name": "support-team", "agent_count": 5, "monthly_cost_usd": 456.78, "created_at": "2026-02-15T08:00:00Z" }, { "id": "team_def456", "name": "sales-team", "agent_count": 3, "monthly_cost_usd": 312.45, "created_at": "2026-02-20T08:00:00Z" } ] } ``` ### Create a Team ``` POST /teams ``` ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/teams \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "engineering-team" }' ``` ### Update a Team ``` PATCH /teams/{team_id} ``` Rename a team. The name must be unique within the tenant. ```bash theme={null} curl -X PATCH https://api.meshai.dev/api/v1/teams/team_abc123 \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "platform-engineering" }' ``` Returns `409 Conflict` if a team with that name already exists. ### Delete a Team ``` DELETE /teams/{team_id} ``` Delete a team. The team must have no agents assigned to it. ```bash theme={null} curl -X DELETE https://api.meshai.dev/api/v1/teams/team_abc123 \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` Returns `204 No Content` on success. Returns `409 Conflict` if the team still has agents assigned. Reassign or remove them first. # Anomalies API Source: https://docs.meshai.dev/api-reference/anomalies List, inspect, acknowledge, and resolve anomalies. Manage anomaly rules. The expanded anomaly pipeline is live. API PR #84 activated the in-app five-minute scheduler on August 11, 2026. Production verification at the 20:20, 20:25, and 20:30 UTC boundaries observed exactly one elected runner per boundary, cycle times of 655 ms, 350 ms, and 490 ms, and no errors. The first cycle created 13 continuity incidents from existing evidence gaps; the next two created no duplicate incidents. ## Detection semantics Reliability baselines are source-specific: proxy and OTLP facts are not blended. Error-rate evaluation requires at least 10 baseline requests and 5 recent requests. Latency evaluation requires at least 10 baseline samples, 5 recent samples, and at least 50% duration coverage in both windows. Missing or invalid duration samples do not prevent error-rate evaluation. When latency is eligible, `details.latency_statistic` is `mean_of_exact_5m_bucket_p95`. MeshAI computes an exact p95 within each five-minute bucket, then compares the mean of those bucket values across the baseline and recent windows. This is not an exact percentile across all requests in the full window. `details` also reports source, sample counts, coverage, and whether error-rate and latency evidence were available. ## List Anomalies ``` GET /anomalies ``` | Parameter | Type | Description | | ---------- | ------- | ------------------------------------------------------------------------ | | `status` | string | `open`, `acknowledged`, `resolved` | | `type` | string | `cost_spike`, `reliability_decay`, `behavioral_drift`, `security_threat` | | `agent_id` | string | Filter to a specific agent | | `severity` | string | `low`, `medium`, `high`, `critical` | | `page` | integer | Page number | | `limit` | integer | Results per page | ```bash theme={null} curl "https://api.meshai.dev/api/v1/anomalies?status=open&type=cost_spike" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": [ { "id": "ano_abc123", "agent_id": "agt_xyz789", "agent_name": "production-summarizer", "anomaly_type": "cost_spike", "severity": "high", "status": "open", "description": "Token spend increased 340% vs 7-day average", "detected_at": "2026-03-17T09:45:00Z", "details": { "current_cost_usd": 45.20, "baseline_cost_usd": 10.30, "deviation_percent": 338.8 } } ], "meta": { "total": 3, "page": 1, "limit": 20 } } ``` ## Get an Anomaly ``` GET /anomalies/{anomaly_id} ``` ```bash theme={null} curl https://api.meshai.dev/api/v1/anomalies/ano_abc123 \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ## Anomaly Summary ``` GET /anomalies/summary ``` Get counts by status and type. ```bash theme={null} curl https://api.meshai.dev/api/v1/anomalies/summary \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "total": 12, "by_status": { "open": 3, "acknowledged": 5, "resolved": 4 }, "by_type": { "cost_spike": 6, "reliability_decay": 3, "behavioral_drift": 2, "security_threat": 1 } } } ``` ## Acknowledge an Anomaly ``` POST /anomalies/{anomaly_id}/acknowledge ``` ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/anomalies/ano_abc123/acknowledge \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "note": "Expected spike, batch processing job" }' ``` ## Resolve an Anomaly ``` POST /anomalies/{anomaly_id}/resolve ``` ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/anomalies/ano_abc123/resolve \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "resolution": "Batch job completed. Cost back to normal." }' ``` ## Anomaly Rules Custom rules let you define thresholds and conditions for anomaly detection beyond the built-in ML algorithms. ### List Rules ``` GET /anomaly-rules ``` ```bash theme={null} curl https://api.meshai.dev/api/v1/anomaly-rules \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### Create a Rule ``` POST /anomaly-rules ``` | Field | Type | Description | | --------------------- | ------- | ------------------------------------------------------------------------ | | `anomaly_type` | string | `cost_spike`, `reliability_decay`, `behavioral_drift`, `security_threat` | | `enabled` | boolean | Defaults to `true` | | `threshold_config` | object | Threshold parameters for the rule | | `notification_config` | object | Optional. Set `webhook_url` to receive delivery notifications | ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/anomaly-rules \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "anomaly_type": "cost_spike", "enabled": true, "threshold_config": { "daily_cost_usd": 100 }, "notification_config": { "webhook_url": "https://example.com/webhooks/meshai" } }' ``` ```json Response theme={null} { "success": true, "data": { "id": 12, "anomaly_type": "cost_spike", "enabled": true, "threshold_config": { "daily_cost_usd": 100 }, "notification_config": { "webhook_url": "https://example.com/webhooks/meshai" }, "created_at": "2026-03-17T10:00:00Z", "updated_at": "2026-03-17T10:00:00Z" } } ``` ### Update a Rule ``` PATCH /anomaly-rules/{rule_id} ``` ```bash theme={null} curl -X PATCH https://api.meshai.dev/api/v1/anomaly-rules/12 \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "threshold_config": { "daily_cost_usd": 150 } }' ``` ### Delete a Rule ``` DELETE /anomaly-rules/{rule_id} ``` ```bash theme={null} curl -X DELETE https://api.meshai.dev/api/v1/anomaly-rules/12 \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` # Authentication Source: https://docs.meshai.dev/api-reference/authentication API keys, scopes, signup, and login for the MeshAI API ## API Keys MeshAI uses Bearer token authentication. All API keys start with `msh_`. ```bash theme={null} curl https://api.meshai.dev/api/v1/agents \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### Key Types | Type | Prefix | Permissions | | ------------- | ------ | ------------------------------------------------------------ | | **Admin** | `msh_` | Full access: manage agents, policies, billing, users | | **Proxy** | `msh_` | Forward LLM requests through the proxy; read-only agent data | | **Read-only** | `msh_` | Read agents, cost, anomalies; no write operations | ### Scopes API keys are scoped to limit permissions: | Scope | Allows | | ------------------ | --------------------------------------------------------- | | `registry:read` | List and get agents, teams | | `registry:write` | Register, update, delete agents and teams | | `telemetry:write` | Send heartbeats and usage data | | `monitoring:read` | Query monitoring overview | | `cost:read` | Query cost endpoints | | `anomaly:read` | List and get anomalies | | `anomaly:write` | Acknowledge, resolve anomalies | | `governance:read` | List policies, approvals, audit events | | `governance:write` | Create policies, decide approvals, classify risk | | `payload:read` | Read the tenant payload-capture configuration | | `payload:write` | Create or update the tenant payload-capture configuration | | `proxy:forward` | Forward LLM requests through the proxy | | `admin` | Full access: manage keys, agents, policies, billing | | `platform:admin` | Tenant management (platform admins only) | ### Scope Restrictions When creating a new API key, the scopes you can grant depend on your own key's permissions: | Your scope | Can grant | | ---------------- | ---------------------------------- | | `platform:admin` | Any scope | | `admin` | All scopes except `platform:admin` | | Other | Only scopes you already have | Attempting to grant a scope you don't have returns `403 Forbidden`. ## Get Current Key Info ``` GET /auth/me ``` Returns the scopes and identity of the API key making the request. Useful for determining which scopes are available when creating new keys. ```bash theme={null} curl https://api.meshai.dev/api/v1/auth/me \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "key_id": "01JABC123DEF456", "tenant_id": "01JXYZ789GHI012", "scopes": ["admin"] } } ``` ## Create an API Key ### Via Dashboard Go to [app.meshai.dev/settings/api-keys](https://app.meshai.dev/settings/api-keys) and click "Create API Key". Select the scopes you need. ### Via API ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/auth/api-keys \ -H "Authorization: Bearer msh_YOUR_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "ci-pipeline-key", "scopes": ["registry:read", "registry:write", "telemetry:write"], "expires_in_days": 90 }' ``` ```json Response theme={null} { "success": true, "data": { "id": "01JABC123DEF456", "raw_key": "msh_abc123def456...", "key_prefix": "msh_abc1", "name": "ci-pipeline-key", "scopes": ["registry:read", "registry:write", "telemetry:write"], "expires_at": "2026-06-15T10:00:00Z", "created_at": "2026-03-17T10:00:00Z" } } ``` The API key is shown once at creation time. Store it securely. You cannot retrieve it later. ## Signup Create a new MeshAI account: ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/auth/signup \ -H "Content-Type: application/json" \ -d '{ "email": "user@company.com", "password": "secure-password", "company_name": "Acme Corp" }' ``` ```json Response theme={null} { "success": true, "data": { "tenant_id": "tnt_abc123", "user_id": "usr_def456", "api_key": "msh_live_abc123def456", "message": "Account created. Check your email to verify." } } ``` ## Login Get a session token for dashboard access or exchange for an API key: ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/auth/login \ -H "Content-Type: application/json" \ -d '{ "email": "user@company.com", "password": "secure-password" }' ``` ```json Response theme={null} { "success": true, "data": { "access_token": "eyJhbGciOi...", "token_type": "bearer", "expires_in": 3600, "tenant_id": "tnt_abc123" } } ``` ## Key Rotation Rotate keys without downtime by creating a new key before deleting the old one: Create a new API key with the same scopes. Deploy the new key to all agents and services. Once all agents are using the new key, delete the old one: ```bash theme={null} curl -X DELETE https://api.meshai.dev/api/v1/auth/api-keys/key_old123 \ -H "Authorization: Bearer msh_YOUR_ADMIN_KEY" ``` ## SAML SSO SAML-based single sign-on for your organization's identity provider. Available on the Enterprise plan (and Enterprise Plus, and internal partner tenants). All SSO endpoints require the `admin` scope. ### Get SSO Configuration ``` GET /sso/config ``` Get the tenant's current SSO configuration, or `null` if SSO has not been configured yet. ```bash theme={null} curl https://api.meshai.dev/api/v1/sso/config \ -H "Authorization: Bearer msh_YOUR_ADMIN_KEY" ``` ```json Response theme={null} { "success": true, "data": { "id": "01JSSO1CONFIG2ABC3DEF456", "provider_name": "Okta", "idp_entity_id": "http://www.okta.com/exkabc123", "idp_sso_url": "https://acme.okta.com/app/acme_meshai/exkabc123/sso/saml", "idp_slo_url": null, "enabled": true, "auto_provision": true, "created_at": "2026-03-01T00:00:00Z" } } ``` ### Configure SSO ``` POST /sso/config ``` Create or update the tenant's SAML SSO configuration. Returns `403` if the tenant's plan does not include SSO. | Field | Type | Required | Description | | ---------------- | ------- | -------- | ----------------------------------------------------- | | `provider_name` | string | Yes | Display name for the identity provider (e.g., `Okta`) | | `idp_entity_id` | string | Yes | IdP entity ID | | `idp_sso_url` | string | Yes | IdP SSO URL | | `idp_slo_url` | string | No | IdP single logout URL | | `idp_x509_cert` | string | Yes | IdP signing certificate | | `auto_provision` | boolean | No | Auto-create users on first SSO login (default `true`) | ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/sso/config \ -H "Authorization: Bearer msh_YOUR_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "provider_name": "Okta", "idp_entity_id": "http://www.okta.com/exkabc123", "idp_sso_url": "https://acme.okta.com/app/acme_meshai/exkabc123/sso/saml", "idp_x509_cert": "-----BEGIN CERTIFICATE-----..." }' ``` ```json Response theme={null} { "success": true, "data": { "id": "01JSSO1CONFIG2ABC3DEF456", "created": true } } ``` ### Enable SSO ``` POST /sso/enable ``` Enable SSO for the tenant. Requires an existing SSO configuration; returns `400` if none exists yet. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/sso/enable \ -H "Authorization: Bearer msh_YOUR_ADMIN_KEY" ``` ### Disable SSO ``` POST /sso/disable ``` Disable SSO for the tenant without deleting its configuration. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/sso/disable \ -H "Authorization: Bearer msh_YOUR_ADMIN_KEY" ``` ### Get SP Metadata ``` GET /sso/metadata ``` Get the MeshAI service provider metadata your identity provider needs to complete the SAML integration. ```bash theme={null} curl https://api.meshai.dev/api/v1/sso/metadata \ -H "Authorization: Bearer msh_YOUR_ADMIN_KEY" ``` ```json Response theme={null} { "success": true, "data": { "entity_id": "https://app.meshai.dev/sso", "acs_url": "https://app.meshai.dev/api/auth/sso/callback", "name_id_format": "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" } } ``` # Billing API Source: https://docs.meshai.dev/api-reference/billing Query billing info, manage checkout, and handle webhooks ## Get Billing Info ``` GET /billing ``` Get the current billing status for your tenant. ```bash theme={null} curl https://api.meshai.dev/api/v1/billing \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "plan": "professional", "active_agents": 47, "agent_limit": 100, "billing_period_start": "2026-03-01T00:00:00Z", "billing_period_end": "2026-03-31T23:59:59Z", "monthly_cost_usd": 799.00, "features": { "anomaly_detection": true, "governance_policies": "unlimited", "hitl_approvals": true, "risk_classification": true, "audit_trail_retention_days": 365, "eu_ai_act_compliance": "basic", "fria_support": false, "incident_reporting": false, "sso": false }, "payment_method": { "type": "card", "last_four": "4242", "expiry": "12/2027" } } } ``` ## Switch Free-Tier Slot ``` PATCH /billing/free-slot ``` Switch which agent occupies the tenant's free-tier agent slot. Requires the `admin` scope. This recovers a free tenant whose first-seen agent was a throwaway, or whose agent identity changed on redeploy, from being locked out of its own free tier. Full recovery when the wrong agent claimed the slot is a 3-step flow: Soft-delete the old (wrong) agent via `DELETE /api/v1/agents/{id}`. Start emitting from the new agent so it exists in the registry. Call this endpoint with the new agent's ID to move the free slot to it. Recording then follows the new agent from the next ingest batch onward. ### Request Body | Field | Type | Required | Description | | ---------- | ------ | -------- | ------------------------------------------------ | | `agent_id` | string | Yes | ULID of the agent that should hold the free slot | ```bash theme={null} curl -X PATCH https://api.meshai.dev/api/v1/billing/free-slot \ -H "Authorization: Bearer msh_YOUR_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "agent_id": "01JABC123DEF456GHI789JKLMN" }' ``` ```json Response theme={null} { "success": true, "data": { "free_agent_id": "01JABC123DEF456GHI789JKLMN" } } ``` ## Checkout (Change Plan) ``` POST /billing/checkout ``` Initiate a plan change. Returns a checkout URL for payment if upgrading, or confirms the downgrade if moving to a lower tier. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/billing/checkout \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "plan": "enterprise" }' ``` ```json Response (upgrade) theme={null} { "success": true, "data": { "action": "upgrade", "from_plan": "professional", "to_plan": "enterprise", "prorated_amount_usd": 1200.00, "checkout_url": "https://checkout.meshai.dev/session/cs_abc123", "expires_at": "2026-03-17T11:00:00Z" } } ``` ```json Response (downgrade) theme={null} { "success": true, "data": { "action": "downgrade", "from_plan": "professional", "to_plan": "starter", "effective_date": "2026-04-01T00:00:00Z", "message": "Downgrade will take effect at the start of the next billing cycle. Ensure you have 25 or fewer active agents by then." } } ``` Valid plan values: `starter`, `professional`, `enterprise`. For Enterprise Plus, [contact sales](mailto:hello@meshai.dev). ## Webhook ``` POST /billing/webhook ``` Endpoint for payment provider webhooks (Stripe). This endpoint is called by the payment provider, not by your application. ### Webhook Events | Event | Description | | ------------------------ | --------------------------------- | | `checkout.completed` | Payment successful, plan upgraded | | `invoice.paid` | Monthly invoice paid | | `invoice.payment_failed` | Payment failed: retry scheduled | | `subscription.canceled` | Subscription canceled | ### Verifying Webhooks MeshAI verifies webhook signatures automatically. If you're self-hosting, configure the webhook signing secret in your environment: ```bash theme={null} STRIPE_WEBHOOK_SECRET=whsec_... ``` ### Webhook Payload Example ```json theme={null} { "event": "checkout.completed", "tenant_id": "tnt_abc123", "plan": "enterprise", "amount_usd": 1999.00, "timestamp": "2026-03-17T10:30:00Z" } ``` # Compliance API Source: https://docs.meshai.dev/api-reference/compliance Article 50 evidence, readiness, GPAI model inventory, FRIA, transparency cards, and incident endpoints ## Article 50 Evidence Pack ``` GET /compliance/article-50/evidence-pack ``` Generate a recorded-evidence report for the AI-disclosure and content-marking tracks. This endpoint requires the `governance:read` scope and a Professional or higher plan. The optional `start` and `end` parameters are ISO 8601 timestamps. The default window is the previous 30 days, and a requested window cannot exceed 395 days. `start` must be earlier than `end`; otherwise the API returns `400`. MeshAI clamps the effective window to the tenant's retained telemetry. Compare `requested_start` and `requested_end` with `effective_start` and `effective_end`; `retention_clamped` is `true` when they differ. ```bash theme={null} curl "https://api.meshai.dev/api/v1/compliance/article-50/evidence-pack?start=2026-08-01T00:00:00Z&end=2026-09-01T00:00:00Z" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` The report uses these honest recorded-evidence statuses: | Status | Meaning | | ---------------------- | ------------------------------------------------------------------------ | | `check_not_configured` | No enabled check or evaluation was recorded | | `no_recorded_evidence` | No passing evidence was recorded, including an empty or skip-only window | | `gaps_recorded` | At least one evaluated interaction recorded a failure | | `evidence_recorded` | Passing evidence was recorded with no recorded failures | Every track reports `applicability: "not_determined"`, and the assessment reports `coverage: "unquantified"`. MeshAI does not infer that Article 50 applies, prove that a disclosure was visible, validate a content mark, or prove that every generated output was evaluated. Missing evidence is not proof of non-compliance. `interactions_with_pass` and `interactions_with_fail` are distinct counts within each result. They can overlap when multiple policies disagree about the same interaction. Review `gaps` before relying on the summaries. The report calls out unquantified coverage, unlinked legacy evaluations, record or inventory truncation, and model-version request fallbacks when present. Per-track `records` contain at most 200 representative interactions, ordered from the earliest evaluation in the effective window. Aggregate counts remain authoritative when `records_truncated` is `true`. The `evidence_integrity` section is also scoped. Hash-chain heads and external checkpoint receipts cover policy evaluations and audit events. They do not cover token usage records or the model inventory. See [Article 50 Transparency Evidence](/governance/article-50-transparency) for instrumentation and dashboard instructions. ## GPAI Model Inventory ``` GET /compliance/model-inventory ``` Return model usage grouped by provider, model, agent, and team. The default period follows your telemetry retention window. You can supply `start` and `end` ISO 8601 timestamps for a period of up to 395 days and `limit` from 1 to 5,000. ```bash theme={null} curl "https://api.meshai.dev/api/v1/compliance/model-inventory?start=2026-08-01T00:00:00Z&end=2026-09-01T00:00:00Z" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` Each row's `attribution_source` is `response` when telemetry supplied `gen_ai.response.model`. It is `request_fallback` when only the requested or directly reported model is known. A fallback row does not confirm the exact model version served by the provider. ```json Response theme={null} { "success": true, "data": { "period_start": "2026-08-01T00:00:00+00:00", "period_end": "2026-09-01T00:00:00+00:00", "generated_at": "2026-09-01T00:00:01+00:00", "distinct_models_returned": 1, "total_rows": 1, "returned_rows": 1, "truncated": false, "model_attribution": { "confirmed": "gen_ai.response.model", "fallback": "gen_ai.request.model or direct telemetry model_name", "warning": "request_fallback rows do not prove the exact model version served by the provider" }, "rows": [ { "provider": "openai", "model": "gpt-4.1-2026-06-15", "attribution_source": "response", "agent_id": "agt_abc123", "agent_name": "production-summarizer", "team_id": "team_platform", "team_name": "Platform", "first_observed_at": "2026-08-10T14:30:00+00:00", "last_observed_at": "2026-08-10T14:30:00+00:00", "requests": 24, "input_tokens": 12000, "output_tokens": 4000, "total_tokens": 16000, "estimated_cost_usd": "0.120000" } ] } } ``` ### Export Model Inventory ``` GET /compliance/model-inventory/export?fmt=csv ``` Download the same inventory as `csv` or `json`. Export requires a Professional or Enterprise plan. The query accepts the same `start`, `end`, and `limit` parameters as the JSON endpoint. ```bash theme={null} curl -OJ "https://api.meshai.dev/api/v1/compliance/model-inventory/export?fmt=csv" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ## Readiness Score ``` GET /compliance/readiness ``` Get the EU AI Act readiness score for your tenant. ```bash theme={null} curl https://api.meshai.dev/api/v1/compliance/readiness \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "total_score": 85, "max_score": 120, "rating": "good", "components": [ { "name": "agent_registry", "score": 20, "max_score": 20, "status": "complete" }, { "name": "risk_classification", "score": 15, "max_score": 20, "status": "partial" }, { "name": "governance_policies", "score": 15, "max_score": 15, "status": "complete" }, { "name": "human_oversight", "score": 15, "max_score": 20, "status": "partial" }, { "name": "audit_trail", "score": 15, "max_score": 15, "status": "complete" }, { "name": "fria_completion", "score": 5, "max_score": 20, "status": "partial" }, { "name": "incident_readiness", "score": 0, "max_score": 10, "status": "missing" } ], "recommendations": [ "Classify the remaining 2 agents with a risk level", "Complete FRIA for agents: hr-screener, loan-evaluator" ], "assessed_at": "2026-03-17T10:00:00Z" } } ``` ## FRIA (Fundamental Rights Impact Assessment) ### Get FRIA ``` GET /agents/{agent_id}/fria ``` ```bash theme={null} curl https://api.meshai.dev/api/v1/agents/agt_abc123/fria \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "id": "fria_abc123", "agent_id": "agt_abc123", "version": 1, "status": "submitted", "processes": "The AI agent reviews job applications...", "frequency_and_scope": "Used daily by 5 HR managers...", "categories_of_persons": "Job applicants...", "specific_risks": "Risk of discriminatory bias...", "human_oversight_measures": "All AI-ranked lists reviewed by human...", "risk_mitigation_measures": "If bias detected: suspend agent...", "created_at": "2026-03-17T10:00:00Z", "created_by": "user@company.com" } } ``` ### Create FRIA ``` POST /agents/{agent_id}/fria ``` All six fields are required. See [FRIA](/governance/fria) for field descriptions. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/agt_abc123/fria \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "processes": "The AI agent reviews job applications and ranks candidates...", "frequency_and_scope": "Used daily by 5 HR managers. ~500 applications/month.", "categories_of_persons": "Job applicants, EU residents of all ages.", "specific_risks": "Risk of discriminatory bias in candidate ranking.", "human_oversight_measures": "All AI-ranked lists reviewed by human HR manager.", "risk_mitigation_measures": "If bias detected: suspend agent, notify applicants." }' ``` ### Submit FRIA ``` POST /fria/{fria_id}/submit ``` Finalizes the FRIA and logs it in the audit trail. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/fria/42/submit \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ## Transparency Card ``` GET /agents/{agent_id}/transparency-card ``` Get the auto-generated transparency card for an agent. ```bash theme={null} curl https://api.meshai.dev/api/v1/agents/agt_abc123/transparency-card \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "agent_id": "agt_abc123", "agent_name": "production-summarizer", "purpose": "Summarizes customer support tickets", "framework": "crewai", "model_provider": "openai", "model_name": "gpt-4o", "risk_level": "limited", "capabilities": ["Text summarization", "Ticket categorization"], "limitations": ["May miss context in multi-language tickets"], "human_oversight": "Output reviewed by support team leads", "data_sources": "Customer support ticket text (no PII stored)", "generated_at": "2026-03-17T10:00:00Z" } } ``` ## Incidents ### Create Incident ``` POST /incidents ``` ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/incidents \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "agent_id": "agt_abc123", "title": "Discriminatory output in hiring agent", "severity": "high", "description": "The HR screening agent systematically ranked female candidates lower...", "impact": "Approximately 120 applicants affected.", "immediate_actions": "Agent suspended immediately.", "root_cause": "Training data contained historical hiring bias.", "affected_persons_count": 120, "involves_health_or_death": false }' ``` ### Get Incident ``` GET /incidents/{incident_id} ``` ```bash theme={null} curl https://api.meshai.dev/api/v1/incidents/inc_abc123 \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### Update Incident ``` PATCH /incidents/{incident_id} ``` ```bash theme={null} curl -X PATCH https://api.meshai.dev/api/v1/incidents/inc_abc123 \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "status": "mitigated", "update_note": "All affected applications manually re-reviewed." }' ``` ### Authority Notification There is no separate notify-authority endpoint. Record that a competent authority has been notified by updating the incident: `PATCH /incidents/{incident_id}` with body field `authority_notified: true`. See [Incident Reporting](/governance/incidents#update-an-incident) for the full workflow and deadlines. # Cost API Source: https://docs.meshai.dev/api-reference/cost Token spend attribution by agent, team, model, and time series ## Cost Summary ``` GET /cost/summary ``` Get aggregate cost data for your tenant. | Parameter | Type | Default | Description | | --------- | ------ | -------------- | ---------------------- | | `period` | string | `month` | `day`, `week`, `month` | | `from` | string | Start of month | ISO 8601 date | | `to` | string | Today | ISO 8601 date | ```bash theme={null} curl "https://api.meshai.dev/api/v1/cost/summary?period=month&from=2026-03-01" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "total_cost_usd": 1245.67, "total_input_tokens": 15234000, "total_output_tokens": 4567000, "total_requests": 8923, "period": "month", "from": "2026-03-01T00:00:00Z", "to": "2026-03-17T23:59:59Z" } } ``` ## Cost by Agent ``` GET /cost/by-agent ``` Break down costs per agent, sorted by cost descending. ```bash theme={null} curl "https://api.meshai.dev/api/v1/cost/by-agent?from=2026-03-01&limit=10" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": [ { "agent_id": "agt_abc123", "agent_name": "production-summarizer", "team": "support-team", "total_cost_usd": 456.78, "input_tokens": 5600000, "output_tokens": 1200000, "requests": 3400 } ], "meta": { "total": 12, "page": 1, "limit": 10 } } ``` ## Cost by Team ``` GET /cost/by-team ``` Break down costs per team. ```bash theme={null} curl "https://api.meshai.dev/api/v1/cost/by-team?from=2026-03-01" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": [ { "team": "support-team", "total_cost_usd": 645.23, "input_tokens": 7800000, "output_tokens": 2100000, "requests": 4500, "agent_count": 5 }, { "team": "sales-team", "total_cost_usd": 412.30, "input_tokens": 5200000, "output_tokens": 1500000, "requests": 2800, "agent_count": 3 } ] } ``` ## Cost by Model ``` GET /cost/by-model ``` Break down costs per model. ```bash theme={null} curl "https://api.meshai.dev/api/v1/cost/by-model?from=2026-03-01" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": [ { "model_provider": "openai", "model_name": "gpt-4o", "total_cost_usd": 890.12, "input_tokens": 10200000, "output_tokens": 3100000, "requests": 5800 }, { "model_provider": "anthropic", "model_name": "claude-sonnet-4-20250514", "total_cost_usd": 355.55, "input_tokens": 5034000, "output_tokens": 1467000, "requests": 3123 } ] } ``` ## Cost Time Series ``` GET /cost/timeseries ``` Get cost data as a time series for charting. | Parameter | Type | Default | Description | | ------------- | ------ | ----------- | -------------------------- | | `granularity` | string | `day` | `hour`, `day`, `week` | | `from` | string | 30 days ago | ISO 8601 date | | `to` | string | Today | ISO 8601 date | | `agent_id` | string | - | Filter to a specific agent | | `team` | string | - | Filter to a specific team | ```bash theme={null} curl "https://api.meshai.dev/api/v1/cost/timeseries?granularity=day&from=2026-03-01" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": [ { "timestamp": "2026-03-01T00:00:00Z", "cost_usd": 72.34, "input_tokens": 890000, "output_tokens": 267000, "requests": 520 }, { "timestamp": "2026-03-02T00:00:00Z", "cost_usd": 68.90, "input_tokens": 845000, "output_tokens": 251000, "requests": 498 } ] } ``` ## Budget Limits Budget limits are an enforcement feature: once configured, the proxy blocks over-budget requests for the scope they apply to (global, a team, or a single agent). Creating or updating a limit requires a plan with enforcement entitlement (Starter and above); free-tier tenants get a `402` upgrade-required error. Reading limits and status, and deleting a limit, only require the `admin` scope. ### List Budget Limits ``` GET /budget/limits ``` List all budget limits configured for your tenant. ```bash theme={null} curl https://api.meshai.dev/api/v1/budget/limits \ -H "Authorization: Bearer msh_YOUR_ADMIN_KEY" ``` ```json Response theme={null} { "success": true, "data": [ { "id": "01JBUDGET1LIMIT2ABC3DEF456", "tenant_id": "01JTENANT123ABC456DEF789", "team_id": null, "agent_id": "agt_abc123", "monthly_limit_usd": 500.00, "warn_threshold_pct": 80, "block_threshold_pct": 100, "enabled": true, "created_at": "2026-03-01T00:00:00Z", "updated_at": "2026-03-01T00:00:00Z" } ] } ``` ### Create a Budget Limit ``` POST /budget/limits ``` Create a budget limit for a scope. Set exactly one of `team_id` or `agent_id` to scope the limit; omit both for a tenant-wide (global) limit. | Field | Type | Required | Description | | --------------------- | ------- | -------- | --------------------------------------------------------------------- | | `team_id` | string | No | Scope the limit to a team | | `agent_id` | string | No | Scope the limit to a single agent | | `monthly_limit_usd` | number | Yes | Monthly spend cap in USD (0-999999) | | `warn_threshold_pct` | integer | No | Percentage of the limit that triggers a warning (default `80`, 1-100) | | `block_threshold_pct` | integer | No | Percentage of the limit that blocks requests (default `100`, 1-200) | | `enabled` | boolean | No | Whether the limit is active (default `true`) | ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/budget/limits \ -H "Authorization: Bearer msh_YOUR_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "agent_id": "agt_abc123", "monthly_limit_usd": 500.00, "warn_threshold_pct": 80, "block_threshold_pct": 100 }' ``` ```json Response theme={null} { "success": true, "data": { "id": "01JBUDGET1LIMIT2ABC3DEF456", "tenant_id": "01JTENANT123ABC456DEF789", "team_id": null, "agent_id": "agt_abc123", "monthly_limit_usd": 500.00, "warn_threshold_pct": 80, "block_threshold_pct": 100, "enabled": true, "created_at": "2026-03-01T00:00:00Z", "updated_at": "2026-03-01T00:00:00Z" } } ``` ### Update a Budget Limit ``` PATCH /budget/limits/{id} ``` Update an existing budget limit. All fields are optional; only the fields you include are changed. | Field | Type | Required | Description | | --------------------- | ------- | -------- | ------------------------------------- | | `monthly_limit_usd` | number | No | Monthly spend cap in USD (0-999999) | | `warn_threshold_pct` | integer | No | Warning threshold percentage (1-100) | | `block_threshold_pct` | integer | No | Blocking threshold percentage (1-200) | | `enabled` | boolean | No | Whether the limit is active | ```bash theme={null} curl -X PATCH https://api.meshai.dev/api/v1/budget/limits/01JBUDGET1LIMIT2ABC3DEF456 \ -H "Authorization: Bearer msh_YOUR_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "monthly_limit_usd": 750.00 }' ``` ```json Response theme={null} { "success": true, "data": { "id": "01JBUDGET1LIMIT2ABC3DEF456", "tenant_id": "01JTENANT123ABC456DEF789", "team_id": null, "agent_id": "agt_abc123", "monthly_limit_usd": 750.00, "warn_threshold_pct": 80, "block_threshold_pct": 100, "enabled": true, "created_at": "2026-03-01T00:00:00Z", "updated_at": "2026-03-18T09:15:00Z" } } ``` ### Delete a Budget Limit ``` DELETE /budget/limits/{id} ``` Delete a budget limit. Requires the `admin` scope. ```bash theme={null} curl -X DELETE https://api.meshai.dev/api/v1/budget/limits/01JBUDGET1LIMIT2ABC3DEF456 \ -H "Authorization: Bearer msh_YOUR_ADMIN_KEY" ``` Returns `204 No Content` on success. ### Budget Status ``` GET /budget/status ``` Get current spend versus limit for every configured scope (global, team, and agent). ```bash theme={null} curl https://api.meshai.dev/api/v1/budget/status \ -H "Authorization: Bearer msh_YOUR_ADMIN_KEY" ``` ```json Response theme={null} { "success": true, "data": { "scopes": [ { "scope": "agent:agt_abc123", "limit_id": "01JBUDGET1LIMIT2ABC3DEF456", "monthly_limit_usd": 750.00, "current_spend_usd": 612.40, "percentage": 81.6, "warn_threshold_pct": 80, "block_threshold_pct": 100, "enabled": true } ] } } ``` # Governance API Source: https://docs.meshai.dev/api-reference/governance Audit trail, risk classification, policies, and approval endpoints ## Audit Trail ### List Audit Events ``` GET /audit-trail ``` | Parameter | Type | Description | | ------------ | ------- | ------------------------------------------------------------ | | `event_type` | string | Filter by type (e.g., `agent.registered`, `policy.violated`) | | `target_id` | string | Filter by target entity ID | | `from` | string | Start date (ISO 8601) | | `to` | string | End date (ISO 8601) | | `page` | integer | Page number | | `limit` | integer | Results per page | ```bash theme={null} curl "https://api.meshai.dev/api/v1/audit-trail?event_type=policy.violated&limit=50" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": [ { "id": "evt_abc123", "event_type": "policy.violated", "actor": "agt_xyz789", "target_id": "pol_def456", "target_type": "policy", "details": { "policy_name": "production-model-allowlist", "violation": "Model gpt-3.5-turbo is not in the allowed list" }, "timestamp": "2026-03-17T10:00:00Z" } ], "meta": { "total": 15, "page": 1, "limit": 50 } } ``` ### Export Audit Events ``` GET /audit-trail/export ``` | Parameter | Type | Description | | ------------ | ------ | --------------------- | | `format` | string | `csv` or `json` | | `from` | string | Start date (ISO 8601) | | `to` | string | End date (ISO 8601) | | `event_type` | string | Filter by type | ```bash theme={null} curl "https://api.meshai.dev/api/v1/audit-trail/export?format=csv&from=2026-01-01" \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -o audit-trail.csv ``` ## Risk Classification ### Get Classification ``` GET /agents/{agent_id}/risk-classification ``` ```bash theme={null} curl https://api.meshai.dev/api/v1/agents/agt_abc123/risk-classification \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### Classify Agent ``` POST /agents/{agent_id}/risk-classification ``` ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/agt_abc123/risk-classification \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "risk_level": "high", "justification": "Agent processes employee performance data" }' ``` ### Get AI Suggestion ``` GET /agents/{agent_id}/risk-suggestion ``` ```bash theme={null} curl https://api.meshai.dev/api/v1/agents/agt_abc123/risk-suggestion \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### List Risk Classifications ``` GET /risk-classifications ``` | Parameter | Type | Description | | ------------ | ------- | -------------------- | | `risk_level` | string | Filter by risk level | | `page` | integer | Page number | | `limit` | integer | Results per page | ```bash theme={null} curl "https://api.meshai.dev/api/v1/risk-classifications?risk_level=high" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### Bulk Classify Agents ``` POST /risk-classifications/bulk ``` Classify up to 100 agents in a single request. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/risk-classifications/bulk \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "classifications": [ { "agent_id": "01HZY8K5G3QJXW7VN2P9Z6M4RT", "risk_level": "high", "justification": "Agent processes employee performance data", "assessed_by": "compliance@company.com" } ] }' ``` ```json Response theme={null} { "success": true, "data": { "created": 1, "updated": 0, "failed": 0 } } ``` ## Policies ### List Policies ``` GET /policies ``` ```bash theme={null} curl https://api.meshai.dev/api/v1/policies \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### Create Policy ``` POST /policies ``` ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/policies \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "production-model-allowlist", "policy_type": "model_allowlist", "config": { "allowed_models": ["gpt-4o", "claude-sonnet-4-20250514"] }, "scope": "global", "enabled": true }' ``` Policy types: `model_allowlist`, `block_provider`, `require_approval`, `budget_limit`, `rate_limit`, `require_human_review`. See [Policies](/governance/policies) for config details. ### Get Policy ``` GET /policies/{policy_id} ``` ### Update Policy ``` PATCH /policies/{policy_id} ``` ```bash theme={null} curl -X PATCH https://api.meshai.dev/api/v1/policies/pol_abc123 \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "enabled": false }' ``` ### Delete Policy ``` DELETE /policies/{policy_id} ``` ```bash theme={null} curl -X DELETE https://api.meshai.dev/api/v1/policies/pol_abc123 \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### List Policy Templates ``` GET /policy-templates ``` Curated starter policies a tenant can add in one click. Instantiate one with the "Create Policy from Template" endpoint below. ```bash theme={null} curl https://api.meshai.dev/api/v1/policy-templates \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### Create Policy from Template ``` POST /policies/from-template/{template_id} ``` Instantiates a starter policy, created disabled so you can review and edit it before enabling. Both fields are optional; omitted values fall back to the template's defaults. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/policies/from-template/approved-model-allowlist \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "my-model-allowlist", "priority": 200 }' ``` ### Dry Run Evaluate ``` POST /policies/evaluate ``` Evaluates all applicable policies for a hypothetical request without creating a proxy request or approval. Useful for testing policy configuration before deploying an agent. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/policies/evaluate \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "agent_id": "01HZY8K5G3QJXW7VN2P9Z6M4RT", "provider": "openai", "model": "gpt-4o", "environment": "production" }' ``` ```json Response theme={null} { "success": true, "data": [ { "policy_id": 3, "policy_name": "production-model-allowlist", "policy_type": "model_allowlist", "result": "pass", "reason": null } ] } ``` ### List Policy Evaluations ``` GET /policy-evaluations ``` | Parameter | Type | Description | | ----------- | ------- | ---------------------- | | `policy_id` | integer | Filter by policy | | `agent_id` | string | Filter by agent | | `result` | string | `pass`, `fail`, `skip` | | `page` | integer | Page number | | `limit` | integer | Results per page | ```bash theme={null} curl "https://api.meshai.dev/api/v1/policy-evaluations?result=fail" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ## Approvals ### List Approvals ``` GET /approvals ``` | Parameter | Type | Description | | ---------- | ------- | ------------------------------------------ | | `status` | string | `pending`, `approved`, `denied`, `expired` | | `agent_id` | string | Filter by agent | | `page` | integer | Page number | | `limit` | integer | Results per page | ```bash theme={null} curl "https://api.meshai.dev/api/v1/approvals?status=pending" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### Pending Approval Count ``` GET /approvals/pending/count ``` ```bash theme={null} curl https://api.meshai.dev/api/v1/approvals/pending/count \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "count": 4 } } ``` ### Get Approval ``` GET /approvals/{request_id} ``` ```bash theme={null} curl https://api.meshai.dev/api/v1/approvals/17 \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### Decide Approval ``` POST /approvals/{approval_id}/decide ``` ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/approvals/apr_abc123/decide \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "decision": "approved", "reason": "Agent configuration verified" }' ``` The `decision` field must be `approved` or `denied`. ## Oversight Metrics ### Agent Oversight Scorecard ``` GET /agents/{agent_id}/oversight ``` | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------- | | `start` | datetime | Window start (default: 30 days ago, max range 180 days) | | `end` | datetime | Window end (default: now) | ```bash theme={null} curl "https://api.meshai.dev/api/v1/agents/agt_abc123/oversight" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` Returns policy evaluation counts and fail rate, approval counts by outcome (including expired and pending), override rate, unattended rate, average approval latency, the number of defer-to-human policies applicable to the agent, its risk level, and whether its review is overdue. See [Oversight Metrics](/governance/oversight-metrics) for metric definitions and window semantics. ### Tenant Oversight Summary ``` GET /oversight/summary ``` Same metrics aggregated tenant-wide, plus `agents_evaluated`. Accepts the same `start` / `end` parameters. ## Incident Evidence Pack ``` GET /incidents/{incident_id}/evidence-pack ``` | Parameter | Type | Description | | -------------- | ------- | ----------------------------------------------------------- | | `window_hours` | integer | Telemetry window before `reported_at` (default 24, max 168) | ```bash theme={null} curl "https://api.meshai.dev/api/v1/incidents/42/evidence-pack?window_hours=48" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` Assembles the incident report, agent and risk-classification snapshot, windowed policy evaluations, approvals with decisions, anomalies, usage totals, the audit trail including operator responses, the linked anomaly, and Article 73 deadline status into one document. Requires Professional plan or above. See [Incident Reporting](/governance/incidents#export-an-evidence-pack) for the full field reference. # Monitoring API Source: https://docs.meshai.dev/api-reference/monitoring Fleet-wide status overview and per-agent health scores ## Fleet Overview ``` GET /monitoring/overview ``` Returns the count of agents in each status across the tenant. ```bash theme={null} curl https://api.meshai.dev/api/v1/monitoring/overview \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "total_agents": 12, "healthy": 9, "degraded": 2, "down": 1, "unknown": 0 } } ``` ## Agent Health Score ``` GET /agents/{agent_id}/health ``` Returns a composite health score (0-100) for a single agent, broken down into reliability, cost efficiency, and performance components. Backed by a 5-minute Redis cache; `cached` indicates whether the score was served from cache or computed fresh. ```bash theme={null} curl https://api.meshai.dev/api/v1/agents/01HQZXK3VJ3XZ9K8QYNPBC7G4T/health \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "agent_id": "01HQZXK3VJ3XZ9K8QYNPBC7G4T", "score": 87, "color": "green", "breakdown": { "reliability": { "score": 92, "weight": 0.4, "details": { "error_rate": 0.02, "uptime_pct": 99.1 } }, "cost_efficiency": { "score": 80, "weight": 0.3, "details": { "daily_cost_trend": -0.05 } }, "performance": { "score": 85, "weight": 0.3, "details": { "avg_latency_ms": 340.2, "p95_latency_ms": 890.5 } } }, "computed_at": "2026-03-17T10:30:00Z", "cached": false } } ``` Returns `404 Not Found` if the agent does not exist in the tenant. # Notifications API Source: https://docs.meshai.dev/api-reference/notifications Manage notification channels for alerts and policy events ## List Channels ``` GET /notifications/channels ``` Sensitive fields in `config` (PagerDuty routing keys, Slack webhook URLs, webhook secrets) are masked in the response. ```bash theme={null} curl https://api.meshai.dev/api/v1/notifications/channels \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": [ { "id": "01HR3A2QK9XZC4M7QYNVTB5R8E", "name": "on-call-pagerduty", "channel_type": "pagerduty", "config": { "routing_key": "R012ABCD...789A" }, "enabled": true, "events": ["policy.violated", "agent.blocked"], "created_at": "2026-03-17T10:00:00Z" } ] } ``` ## Create a Channel ``` POST /notifications/channels ``` `channel_type` must be `pagerduty`, `slack`, `webhook`, or `email`. Any webhook URL in `config` is validated at creation time to guard against SSRF. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/notifications/channels \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "on-call-pagerduty", "channel_type": "pagerduty", "config": { "routing_key": "R012ABCD1234EFGH56789A" }, "enabled": true, "events": ["policy.violated", "agent.blocked"] }' ``` ```json Response theme={null} { "success": true, "data": { "id": "01HR3A2QK9XZC4M7QYNVTB5R8E", "name": "on-call-pagerduty", "channel_type": "pagerduty" } } ``` ## Update a Channel ``` PATCH /notifications/channels/{channel_id} ``` `channel_type` cannot be changed after creation. Any of `name`, `config`, `enabled`, `events` may be updated. ```bash theme={null} curl -X PATCH https://api.meshai.dev/api/v1/notifications/channels/01HR3A2QK9XZC4M7QYNVTB5R8E \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "enabled": false }' ``` ## Delete a Channel ``` DELETE /notifications/channels/{channel_id} ``` ```bash theme={null} curl -X DELETE https://api.meshai.dev/api/v1/notifications/channels/01HR3A2QK9XZC4M7QYNVTB5R8E \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` Returns `204 No Content` on success. ## Send a Test Notification ``` POST /notifications/channels/{channel_id}/test ``` Sends a test payload through the channel to verify its configuration. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/notifications/channels/01HR3A2QK9XZC4M7QYNVTB5R8E/test \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "success": true, "message": "Test notification sent" } } ``` If delivery fails, the endpoint still returns `200 OK` with `success: false` and a `message` explaining the failure, rather than an HTTP error. # API Overview Source: https://docs.meshai.dev/api-reference/overview Base URL, authentication, response format, and pagination for the MeshAI API ## Base URL All API requests use the following base URL: ``` https://api.meshai.dev/api/v1 ``` ## Authentication Include your API key as a Bearer token in the `Authorization` header: ```bash theme={null} curl https://api.meshai.dev/api/v1/agents \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` API keys start with `msh_`. Create keys in the dashboard at **Settings → API Keys**. See [Authentication](/api-reference/authentication) for key types, scopes, and signup/login endpoints. ## Response Format All responses use a consistent envelope: ### Success ```json theme={null} { "success": true, "data": { ... } } ``` ### Success (Paginated) ```json theme={null} { "success": true, "data": [ ... ], "meta": { "total": 150, "page": 1, "limit": 20 } } ``` ### Error ```json theme={null} { "success": false, "error": "Human-readable error message", "code": "VALIDATION_ERROR" } ``` ## Common Error Codes | HTTP Status | Code | Description | | ----------- | -------------------- | ------------------------------------------------------------- | | 400 | `VALIDATION_ERROR` | Invalid request body or parameters | | 401 | `UNAUTHORIZED` | Missing or invalid API key | | 402 | `PLAN_LIMIT_REACHED` | Agent limit or feature not available on your plan | | 403 | `FORBIDDEN` | Insufficient permissions or policy violation | | 404 | `NOT_FOUND` | Resource not found | | 409 | `CONFLICT` | Resource already exists (e.g., duplicate agent name) | | 429 | `RATE_LIMITED` | Too many requests: retry after the `Retry-After` header value | | 500 | `INTERNAL_ERROR` | Server error: contact support | ## Pagination List endpoints support pagination with `page` and `limit` query parameters: ```bash theme={null} curl "https://api.meshai.dev/api/v1/agents?page=2&limit=50" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` | Parameter | Type | Default | Description | | --------- | ------- | ------- | -------------------------- | | `page` | integer | 1 | Page number (1-based) | | `limit` | integer | 20 | Results per page (max 100) | The response `meta` object contains the total count for building pagination UI. ## Rate Limits | Plan | Requests/min | | --------------- | ------------ | | Starter | 60 | | Professional | 300 | | Enterprise | 1,000 | | Enterprise Plus | Custom | Rate-limited responses include a `Retry-After` header (seconds). ## Content Type All POST/PATCH/PUT requests must include: ``` Content-Type: application/json ``` # Payload Capture API Source: https://docs.meshai.dev/api-reference/payload-capture Configure opt-in, sanitized input payload capture Payload capture is off by default. These endpoints configure capture only. MeshAI does not currently expose captured payload records through a public read or export endpoint. Enabling capture is a tenant processing instruction, not proof of end-user consent or another lawful basis. Your organization remains responsible for establishing and documenting its lawful basis. ## Get Configuration ``` GET /payload-capture/config ``` Requires `payload:read`. An unconfigured tenant receives the default-off response: ```bash theme={null} curl https://api.meshai.dev/api/v1/payload-capture/config \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "enabled": false, "configured": false, "maximum_retention_days": 30, "legal_basis_notice": "Enabling capture is a tenant processing instruction, not proof of end-user consent or another lawful basis. The tenant remains responsible for that basis." } } ``` ## Update Configuration ``` PUT /payload-capture/config ``` Requires `payload:write`. `retention_days` must be from 1 through 30 and cannot exceed the tenant plan's telemetry retention. `processing_purpose` must contain 10 through 500 characters. You can provide up to 25 redaction rules with unique IDs. ```bash theme={null} curl -X PUT https://api.meshai.dev/api/v1/payload-capture/config \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "enabled": true, "retention_days": 7, "processing_purpose": "Audit regulated agent input evidence", "redaction_rules": [ { "id": "customer.account", "field_path": "messages.content", "pattern": "account-[0-9]+" } ] }' ``` ```json Response theme={null} { "success": true, "data": { "configured": true, "enabled": true, "retention_days": 7, "processing_purpose": "Audit regulated agent input evidence", "redaction_rules": [ { "id": "customer.account", "field_path": "messages.content", "pattern": "account-[0-9]+" } ], "config_version": 1, "updated_by": "01JKEY0000000000000000001", "created_at": "2026-08-10T14:30:00Z", "updated_at": "2026-08-10T14:30:00Z", "maximum_retention_days": 30, "legal_basis_notice": "Enabling capture is a tenant processing instruction, not proof of end-user consent or another lawful basis. The tenant remains responsible for that basis." } } ``` A rule `field_path` is a dot-separated sequence of field names, such as `messages.content`. Array selectors such as `messages[*].content` are not accepted. `pattern`, when supplied, must be a valid regular expression no longer than 500 characters. Each update increments `config_version` and creates a `payload_capture.configured` audit event. To disable future capture, send the same required fields with `enabled: false`; `retention_days` and `processing_purpose` remain required. The disabled configuration stops requests that read it from starting capture, but work already in flight or queued can still finish. Disabling does not delete existing sanitized records. Each record receives an `expires_at` value from the retention setting in effect when it was written, so a later retention change applies only to new records. Expiry makes the record eligible for scheduled deletion; it is not a guarantee of deletion at that exact instant. There is currently no public payload read, export, delete, or self-service data-subject-request endpoint. See [Sanitized Input Capture](/governance/payload-capture) for supported inputs, redaction, and failure semantics. # Proxy API Source: https://docs.meshai.dev/api-reference/proxy Proxy keys, managed provider keys, and proxy usage stats Creating a proxy key or managed key puts MeshAI's proxy in front of an agent, which enables enforcement (budget blocking, policy enforcement). Both require Starter plan or above; free tenants get a `402` upgrade-required response. ## Proxy Keys ### Create a Proxy Key ``` POST /proxy-keys ``` Creates a proxy key for developer attribution. An agent is auto-created behind the key if one doesn't already exist. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/proxy-keys \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "developer_label": "jane-dev", "allowed_providers": ["openai", "anthropic"], "budget_limit_usd": 100.00, "expires_in_days": 90 }' ``` ```json Response theme={null} { "success": true, "data": { "api_key_id": "01HR2Y8QZKJ6XM4P9VNTWB3F7C", "key_prefix": "msh_a1b2", "developer_label": "jane-dev", "team_id": null, "agent_id": "01HQZXK3VJ3XZ9K8QYNPBC7G4T", "allowed_providers": ["openai", "anthropic"], "budget_limit_usd": 100.00, "allowed_models": null, "model_overrides": null, "rate_limit_override": null, "use_managed_key": false, "created_at": "2026-03-17T10:00:00Z", "raw_key": "msh_a1b2c3d4e5f6g7h8i9j0" } } ``` The `raw_key` is shown once, at creation time. Store it securely; it cannot be retrieved again. ### List Proxy Keys ``` GET /proxy-keys ``` ```bash theme={null} curl https://api.meshai.dev/api/v1/proxy-keys \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### Revoke a Proxy Key ``` DELETE /proxy-keys/{api_key_id} ``` ```bash theme={null} curl -X DELETE https://api.meshai.dev/api/v1/proxy-keys/01HR2Y8QZKJ6XM4P9VNTWB3F7C \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` Returns `204 No Content` on success. ## Proxy Stats ``` GET /proxy/stats ``` Today's proxy usage totals for the tenant. ```bash theme={null} curl https://api.meshai.dev/api/v1/proxy/stats \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "total_requests_today": 1842, "total_tokens_today": 512340, "total_cost_today_usd": "12.4501", "active_proxy_keys": 6 } } ``` ## Managed Provider Keys Managed keys let MeshAI's proxy call a provider on the tenant's behalf using a key stored in AWS Secrets Manager. Only a secret reference is stored in MeshAI; the key value itself never passes through the API. ### Create a Managed Key ``` POST /managed-keys ``` `secret_ref` must be an AWS Secrets Manager name or ARN under the `meshai/managed/` prefix. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/managed-keys \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "provider": "openai", "label": "org-openai-key", "secret_ref": "meshai/managed/acme-corp/openai" }' ``` ```json Response theme={null} { "success": true, "data": { "id": "01HR33F9K7WZC2M8QXNVBT5R6D", "provider": "openai", "label": "org-openai-key", "created_at": "2026-03-17T10:00:00Z" } } ``` ### List Managed Keys ``` GET /managed-keys ``` ```bash theme={null} curl https://api.meshai.dev/api/v1/managed-keys \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### Delete a Managed Key ``` DELETE /managed-keys/{managed_key_id} ``` ```bash theme={null} curl -X DELETE https://api.meshai.dev/api/v1/managed-keys/01HR33F9K7WZC2M8QXNVBT5R6D \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` Returns `204 No Content` on success. # Security API Source: https://docs.meshai.dev/api-reference/security Kill switch, quarantine, lifecycle, ownership, relationships, and security posture All endpoints on this page except the read-only ownership and relationship lookups require the `admin` scope. ## Kill Switch ### Block an Agent ``` POST /agents/{agent_id}/block ``` Immediately blocks the agent from making requests through the proxy. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/01HQZXK3VJ3XZ9K8QYNPBC7G4T/block \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "reason": "Suspected credential leak" }' ``` ### Unblock an Agent ``` POST /agents/{agent_id}/unblock ``` ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/01HQZXK3VJ3XZ9K8QYNPBC7G4T/unblock \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ## Quarantine ### Quarantine an Agent ``` POST /agents/{agent_id}/quarantine ``` Flags a shadow or misbehaving agent as quarantined and blocks it in the proxy layer. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/01HQZXK3VJ3XZ9K8QYNPBC7G4T/quarantine \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "reason": "Unregistered agent discovered calling production models" }' ``` ### Release from Quarantine ``` POST /agents/{agent_id}/release-quarantine ``` ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/01HQZXK3VJ3XZ9K8QYNPBC7G4T/release-quarantine \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### List Quarantined Agents ``` GET /agents/quarantined ``` ```bash theme={null} curl https://api.meshai.dev/api/v1/agents/quarantined \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ## Lifecycle ### List Expired Agents ``` GET /agents/expired ``` Agents whose `expires_at` has passed. ```bash theme={null} curl https://api.meshai.dev/api/v1/agents/expired \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### List Agents Due for Review ``` GET /agents/due-review ``` Agents whose `review_date` has passed. ```bash theme={null} curl https://api.meshai.dev/api/v1/agents/due-review \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### Configure Lifecycle ``` PATCH /agents/{agent_id}/lifecycle ``` Sets an agent's expiry date, access review cadence, and/or sponsor. All fields are optional; `review_frequency` must be `weekly`, `monthly`, `quarterly`, or `annually` and drives the computed `review_date`. ```bash theme={null} curl -X PATCH https://api.meshai.dev/api/v1/agents/01HQZXK3VJ3XZ9K8QYNPBC7G4T/lifecycle \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "expires_at": "2026-12-31T00:00:00Z", "review_frequency": "quarterly", "sponsor_id": "hcunha" }' ``` ## Ownership (ABAC) ### Assign an Owner ``` POST /agents/{agent_id}/owners ``` `owner_type` must be `user`, `team`, or `service_account`. `owner_id` is a caller-supplied external identifier (e.g. an SSO user ID), not a MeshAI-generated ID. `permissions` defaults to `{"can_invoke": true, "can_configure": false, "can_delete": false}` when omitted. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/01HQZXK3VJ3XZ9K8QYNPBC7G4T/owners \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "owner_type": "user", "owner_id": "sso-user-4821", "owner_name": "Jane Doe" }' ``` ### List Agent Owners ``` GET /agents/{agent_id}/owners ``` Requires the `registry:read` scope. ```bash theme={null} curl https://api.meshai.dev/api/v1/agents/01HQZXK3VJ3XZ9K8QYNPBC7G4T/owners \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### Remove an Owner ``` DELETE /agents/{agent_id}/owners/{owner_id} ``` `owner_id` here is the integer ID of the ownership record returned by `POST /agents/{agent_id}/owners` (not the external `owner_id` string). ```bash theme={null} curl -X DELETE https://api.meshai.dev/api/v1/agents/01HQZXK3VJ3XZ9K8QYNPBC7G4T/owners/7 \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` Returns `204 No Content` on success. ### List Agents by Owner ``` GET /owners/{owner_id}/agents ``` Requires the `registry:read` scope. `owner_id` is the external identifier used when the owner was assigned. ```bash theme={null} curl https://api.meshai.dev/api/v1/owners/sso-user-4821/agents \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ## Relationships ### Agent Relationships ``` GET /agents/{agent_id}/relationships ``` Requires the `registry:read` scope. Lists the models, providers, tools, and other agents this agent calls. ```bash theme={null} curl https://api.meshai.dev/api/v1/agents/01HQZXK3VJ3XZ9K8QYNPBC7G4T/relationships \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ### Relationship Graph ``` GET /relationships/graph ``` Requires the `registry:read` scope. Returns the full tenant-wide agent dependency graph as nodes and edges. ```bash theme={null} curl https://api.meshai.dev/api/v1/relationships/graph \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "nodes": [ { "id": "01HQZXK3VJ3XZ9K8QYNPBC7G4T", "name": "production-summarizer", "type": "agent", "status": "healthy", "blocked": false, "framework": "crewai" }, { "id": "model:gpt-4o", "name": "gpt-4o", "type": "model" } ], "edges": [ { "source": "01HQZXK3VJ3XZ9K8QYNPBC7G4T", "target": "model:gpt-4o", "type": "calls_model", "request_count": 1204 } ] } } ``` ## Security Posture ``` GET /security/posture ``` Composite tenant security score (0-100) across six weighted dimensions: agent ownership, agent expiry, access reviews, quarantine status, kill switch status, and risk classification coverage. ```bash theme={null} curl https://api.meshai.dev/api/v1/security/posture \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "score": 78, "max_score": 100, "components": [ { "name": "Agent Ownership", "max_score": 20, "score": 16, "detail": "8/10 agents have assigned owners" }, { "name": "Agent Expiry", "max_score": 15, "score": 15, "detail": "No expired agents" }, { "name": "Access Reviews", "max_score": 15, "score": 12, "detail": "1 overdue" }, { "name": "Quarantine Status", "max_score": 15, "score": 15, "detail": "None quarantined" }, { "name": "Kill Switch Status", "max_score": 15, "score": 10, "detail": "1 agents blocked" }, { "name": "Risk Classification", "max_score": 20, "score": 10, "detail": "5/10 agents classified" } ], "assessed_at": "2026-03-17T10:30:00Z" } } ``` # Telemetry API Source: https://docs.meshai.dev/api-reference/telemetry Send heartbeats and report token usage ## Send Heartbeat ``` POST /telemetry/heartbeat ``` Report that an agent is alive. Updates the agent's `last_heartbeat` timestamp and sets status to `healthy`. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/telemetry/heartbeat \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "agent_id": "agt_abc123" }' ``` ```json Response theme={null} { "success": true, "data": { "agent_id": "agt_abc123", "status": "healthy", "last_heartbeat": "2026-03-17T10:30:00Z" } } ``` ### Status Transitions | Condition | Status | | ----------------------------------- | ---------- | | Heartbeat received within 2 minutes | `healthy` | | No heartbeat for 2–5 minutes | `degraded` | | No heartbeat for 5+ minutes | `down` | | Never sent a heartbeat | `unknown` | ## Send Heartbeats (Batch) ``` POST /telemetry/heartbeats ``` Report multiple agent heartbeats in a single request. Requires the `telemetry:write` scope. ### Request Body | Field | Type | Required | Description | | ------------ | ----- | -------- | ---------------------------------------------------------------------- | | `heartbeats` | array | Yes | Up to 100 heartbeat objects, same shape as `POST /telemetry/heartbeat` | Each heartbeat object: | Field | Type | Required | Description | | ------------ | ------- | -------- | ------------------------------------------- | | `agent_id` | string | Yes | Agent ID | | `status` | string | Yes | `healthy`, `degraded`, `down`, or `unknown` | | `latency_ms` | integer | No | Latency in milliseconds (0-3,600,000) | | `metadata` | object | No | Arbitrary key-value metadata | ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/telemetry/heartbeats \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "heartbeats": [ { "agent_id": "agt_abc123", "status": "healthy", "latency_ms": 120 }, { "agent_id": "agt_def456", "status": "degraded", "latency_ms": 850 } ] }' ``` ```json Response theme={null} { "success": true, "data": { "recorded": 2 } } ``` Maximum **100 heartbeats** per batch request. ## Report Single Usage ``` POST /telemetry/usage ``` Report a single LLM API call with token counts and optional cost. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/telemetry/usage \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "agent_id": "agt_abc123", "model_provider": "openai", "model_name": "gpt-4o", "input_tokens": 1500, "output_tokens": 800, "request_type": "chat.completions", "cost_usd": 0.035 }' ``` ### Request Body | Field | Type | Required | Description | | ---------------- | ------- | -------- | ---------------------------------------------------------- | | `agent_id` | string | Yes | Agent ID | | `model_provider` | string | Yes | `openai`, `anthropic`, `google`, `nvidia`, `bedrock` | | `model_name` | string | Yes | Model identifier (e.g., `gpt-4o`) | | `input_tokens` | integer | Yes | Input/prompt token count | | `output_tokens` | integer | Yes | Output/completion token count | | `request_type` | string | No | e.g., `chat.completions`, `embeddings` | | `cost_usd` | float | No | Explicit cost. If omitted, calculated from pricing tables. | ```json Response theme={null} { "success": true, "data": { "id": "usg_abc123", "agent_id": "agt_abc123", "model_provider": "openai", "model_name": "gpt-4o", "input_tokens": 1500, "output_tokens": 800, "cost_usd": 0.035, "recorded_at": "2026-03-17T10:30:00Z" } } ``` ## Report Batch Usage ``` POST /telemetry/usages ``` Report multiple usage events in a single request. More efficient than sending individual events. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/telemetry/usages \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "usages": [ { "agent_id": "agt_abc123", "model_provider": "openai", "model_name": "gpt-4o", "input_tokens": 1500, "output_tokens": 800 }, { "agent_id": "agt_abc123", "model_provider": "openai", "model_name": "gpt-4o-mini", "input_tokens": 500, "output_tokens": 200 }, { "agent_id": "agt_def456", "model_provider": "anthropic", "model_name": "claude-sonnet-4-20250514", "input_tokens": 2000, "output_tokens": 1200 } ] }' ``` ```json Response theme={null} { "success": true, "data": { "accepted": 3, "rejected": 0, "errors": [] } } ``` Maximum **100 events** per batch request. Events that fail validation are reported in the `errors` array but do not block the rest of the batch. # Plans & Pricing Source: https://docs.meshai.dev/billing/plans Five tiers to match your AI agent deployment - from a free trial to enterprise MeshAI offers a free tier plus four paid plans based on the number of agents and features you need. ## Plan Comparison | Feature | Free | Starter | Professional | Enterprise | Enterprise Plus | | --------------------------------------------------- | ------------------ | -------- | ------------ | ---------- | --------------- | | **Price** | \$0 | \$299/mo | \$799/mo | \$1,999/mo | Custom | | **Agents** | 1 | Up to 25 | Up to 100 | Unlimited | Unlimited | | **Agent Registry** | Yes | Yes | Yes | Yes | Yes | | **Cost Attribution** | Yes | Yes | Yes | Yes | Yes | | **Basic Monitoring** | Yes | Yes | Yes | Yes | Yes | | **Proxy (Zero-Code)** | Yes | Yes | Yes | Yes | Yes | | **OTLP Ingest** | Yes (rate-limited) | Yes | Yes | Yes | Yes | | **Python SDK** | Yes | Yes | Yes | Yes | Yes | | **Proxy Enforcement** (budgets, blocking, policies) | - | Yes | Yes | Yes | Yes | | **ML Anomaly Detection** | - | - | Yes | Yes | Yes | | **Ghost Break Alerts** | - | - | Yes | Yes | Yes | | **Governance Policies** | - | Yes | Yes | Yes | Yes | | **HITL Approvals** | - | Yes | Yes | Yes | Yes | | **Risk Classification** | - | Yes | Yes | Yes | Yes | | **Audit Trail Retention** | 7 days | 90 days | 395 days | Unlimited | Unlimited | | **Compliance Exports** | - | - | Yes | Yes | Yes | | **SSO / SAML** | - | - | - | Yes | Yes | | **Dedicated Support** | - | - | - | - | Yes | | **On-premise Option** | - | - | - | - | Yes | ## Free - \$0 For trying MeshAI with a single agent. **1 agent**, basic registry and monitoring, and OTLP ingest at a rate-limited ceiling. No compliance exports and no proxy enforcement (budgets, blocking, policies are not enforced at this tier). ## Starter - \$299/mo Best for teams getting started with AI agent monitoring. Up to **25 agents** with core registry, cost attribution, basic monitoring, and proxy enforcement. ## Professional - \$799/mo Best for growing teams that need anomaly detection and governance. Up to **100 agents** with ML-powered anomaly detection, governance policies, HITL approvals, risk classification, and compliance exports. ## Enterprise - \$1,999/mo Best for organizations with compliance requirements at scale. **Unlimited agents**, unlimited audit trail retention, SSO, and everything in Professional. ## Enterprise Plus - Custom Pricing Best for large enterprises with advanced requirements. **Unlimited agents**, dedicated support, and an on-premise deployment option. [Contact sales](mailto:hello@meshai.dev) for Enterprise Plus pricing. ## Billing Details * All paid plans are billed **monthly** * Annual billing available with **2 months free** (contact sales) * Prices in USD * No long-term contracts - cancel anytime * Usage is measured by the number of **active agents** (agents that sent at least one heartbeat or telemetry event in the billing period) ## Switching Plans Upgrade or downgrade at any time from **Settings → Billing** in the dashboard, or via `POST /billing/checkout` with `plan` set to `starter`, `professional`, or `enterprise` (Enterprise Plus is arranged directly with sales). Changes take effect at the start of the next billing cycle. When upgrading, the prorated difference is charged immediately. # Usage Limits Source: https://docs.meshai.dev/billing/usage-limits Agent limits per plan and what happens when you reach them Each MeshAI plan includes a maximum number of active agents. An **active agent** is any agent that sent at least one heartbeat or telemetry event during the current billing period. ## Limits by Plan | Plan | Agent Limit | Audit Retention | Compliance Exports | OTLP Ingest | | --------------- | ----------- | --------------- | ------------------ | ------------------------------------------------------------ | | Free | 1 | 7 days | Unavailable | Rate-limited (default: 300 spans/min sustained, burst 1,500) | | Starter | 25 | 90 days | Unavailable | Unlimited | | Professional | 100 | 395 days | Yes | Unlimited | | Enterprise | Unlimited | Unlimited | Yes | Unlimited | | Enterprise Plus | Unlimited | Unlimited | Yes | Unlimited | ## What Happens When You Hit the Limit When you reach your plan's agent limit: 1. **Existing agents continue working** - monitoring, policies, and proxy routing are unaffected for already-registered agents. 2. **New registrations are blocked** - attempts to register a new agent return a `402` error: ```json theme={null} { "success": false, "error": "Agent limit reached. Your Starter plan allows 25 agents. Upgrade to register more.", "current_count": 25, "plan_limit": 25, "upgrade_url": "https://app.meshai.dev/settings" } ``` 3. **Dashboard notification** - a banner appears in the dashboard when you're at 80% and 100% of your limit. ## Checking Your Usage ```bash curl theme={null} curl https://api.meshai.dev/api/v1/billing \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") billing = client.get_billing_info() # billing["active_agents"] → 23 # billing["agent_limit"] → 25 ``` ```json Response theme={null} { "success": true, "data": { "plan": "starter", "active_agents": 23, "agent_limit": 25, "billing_period_start": "2026-03-01T00:00:00Z", "billing_period_end": "2026-03-31T23:59:59Z", "monthly_cost_usd": 299.00 } } ``` ## How to Upgrade Navigate to [app.meshai.dev/settings](https://app.meshai.dev/settings). Choose the plan that fits your agent count. The prorated difference is charged immediately. Your new limit takes effect immediately. You can register additional agents right away. You can also upgrade programmatically: ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/billing/checkout \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "plan": "professional" }' ``` ## Deactivating Agents If you don't want to upgrade, you can free up slots by deleting agents you no longer need: ```bash theme={null} curl -X DELETE https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` Deleted agents are removed from your active count immediately but remain in the audit trail for compliance purposes. # Agno Source: https://docs.meshai.dev/framework-guides/agno Auto-track LLM calls in Agno (formerly Phidata) agents ## Installation ```bash theme={null} pip install meshai-sdk[agno] ``` ## Usage ```python theme={null} from meshai import MeshAI from meshai.integrations.agno import track_agno from agno.agent import Agent from agno.models.openai import OpenAIChat client = MeshAI(api_key="msh_...", agent_name="my-agno-agent") client.register(framework="agno") # Enable global tracking track_agno(client) # Run your agents as normal agent = Agent( model=OpenAIChat(id="gpt-4o"), instructions=["You are a helpful assistant"], ) response = agent.run("What is AI governance?") # Model and tokens tracked automatically ``` ## How It Works `track_agno` patches `Agent.run()` to intercept LLM calls. After each agent run, it: 1. Extracts the **model name** from the agent's model configuration 2. Extracts **token counts** from the response usage metrics 3. Infers the **provider** from the model name 4. Sends the usage event to MeshAI (buffered, non-blocking) Works with all Agno-supported model providers: OpenAI, Anthropic, Google, Groq, and others. ## Phidata Compatibility If you are migrating from Phidata, the same integration works. Agno is Phidata's successor and shares the same agent interface. ## Alternative: Proxy (Zero-Code) If your Agno agents use OpenAI or Anthropic, route through the proxy: ```bash theme={null} export OPENAI_BASE_URL=https://proxy.meshai.dev/v1/openai/k/msh_YOUR_PROXY_KEY ``` # Anthropic Source: https://docs.meshai.dev/framework-guides/anthropic Auto-track all Anthropic Claude API calls ## Installation ```bash theme={null} pip install meshai-sdk[anthropic] ``` ## Usage ```python theme={null} from meshai import MeshAI from meshai.integrations.anthropic import wrap_anthropic import anthropic client = MeshAI(api_key="msh_...", agent_name="my-agent") client.register(framework="custom", model_provider="anthropic") ant = wrap_anthropic(anthropic.Anthropic(), meshai=client) response = ant.messages.create( model="claude-sonnet-4-6", max_tokens=1024, messages=[{"role": "user", "content": "Hello"}], ) # Model, input/output tokens captured automatically ``` ## Alternative: Proxy (Zero-Code) ```bash theme={null} export ANTHROPIC_BASE_URL=https://proxy.meshai.dev/v1/anthropic/k/msh_YOUR_PROXY_KEY ``` # AutoGen Source: https://docs.meshai.dev/framework-guides/autogen Auto-track LLM calls in AutoGen multi-agent conversations ## Installation ```bash theme={null} pip install meshai-sdk[autogen] ``` ## Usage ```python theme={null} from meshai import MeshAI from meshai.integrations.autogen import track_autogen client = MeshAI(api_key="msh_...", agent_name="my-autogen-team") client.register(framework="autogen") # Enable global tracking track_autogen(client) # Run AutoGen agents as normal from autogen import AssistantAgent, UserProxyAgent assistant = AssistantAgent("assistant", llm_config={"model": "gpt-4o"}) user_proxy = UserProxyAgent("user_proxy") user_proxy.initiate_chat(assistant, message="Write a poem") # All LLM calls tracked with model and token counts ``` ## How It Works AutoGen logs LLM calls via Python's `logging` module. MeshAI adds a custom handler that: 1. Captures `LLMCall` events from the `autogen_core` logger 2. Extracts **model**, **tokens**, and **provider** from each event 3. Sends to MeshAI (buffered, non-blocking) ## AG2 Compatibility The integration also works with AG2 (AutoGen's fork). The logging interface is compatible. # AWS Bedrock Source: https://docs.meshai.dev/framework-guides/bedrock Auto-track all AWS Bedrock LLM calls ## Installation ```bash theme={null} pip install meshai-sdk[bedrock] ``` ## Usage ```python theme={null} from meshai import MeshAI from meshai.integrations.bedrock import wrap_bedrock import boto3 client = MeshAI(api_key="msh_...", agent_name="my-agent") client.register(framework="custom", model_provider="aws") # Wrap the Bedrock client bedrock = wrap_bedrock( boto3.client("bedrock-runtime"), meshai=client, ) # Use converse(), auto-tracked response = bedrock.converse( modelId="anthropic.claude-sonnet-4-6-20250514-v1:0", messages=[{"role": "user", "content": [{"text": "Hello"}]}], ) # invoke_model() is also tracked response = bedrock.invoke_model( modelId="amazon.titan-text-express-v1", body='{"inputText": "Hello"}', ) ``` ## How It Works `wrap_bedrock` patches both `converse()` and `invoke_model()` on the Bedrock runtime client. After each call, it: 1. Extracts the **model name** from the `modelId` parameter 2. Extracts **token counts** from the response usage metadata 3. Infers the **provider** from the model ID prefix (e.g., `anthropic.`, `amazon.`, `meta.`) 4. Sends the usage event to MeshAI (buffered, non-blocking) ## Alternative: Proxy (Zero-Code) For Bedrock, the proxy approach requires configuring a custom endpoint in your boto3 client. The region must be part of the path: ```python theme={null} bedrock = boto3.client( "bedrock-runtime", endpoint_url="https://proxy.meshai.dev/v1/bedrock/k/msh_YOUR_PROXY_KEY/us-east-1", ) ``` # CrewAI Source: https://docs.meshai.dev/framework-guides/crewai Auto-track all LLM calls in CrewAI crews ## Installation ```bash theme={null} pip install meshai-sdk[crewai] ``` ## Usage ```python theme={null} from meshai import MeshAI from meshai.integrations.crewai import track_crewai client = MeshAI(api_key="msh_...", agent_name="my-crew") client.register(framework="crewai") # Enable global tracking, applies to ALL crews track_crewai(client) # Run your crew as normal from crewai import Agent, Task, Crew researcher = Agent(role="Researcher", llm="gpt-4o", ...) writer = Agent(role="Writer", llm="claude-sonnet-4-6", ...) crew = Crew(agents=[researcher, writer], tasks=[...]) result = crew.kickoff() # Each agent's LLM calls tracked with their specific model ``` ## How It Works MeshAI registers a global `after_llm_call` hook with CrewAI. After every LLM interaction, the hook: 1. Extracts the **model name** from the LLM context 2. Extracts **token counts** from the response 3. Infers the **provider** from the model name 4. Sends the usage event to MeshAI (buffered, batched) This means each agent in your crew is tracked with its own model, no hardcoding needed. ## Multi-Model Crews CrewAI crews often use different models per agent. MeshAI tracks each one separately: ``` Dashboard shows: researcher (gpt-4o) → 15,000 tokens, $0.45 writer (claude-sonnet) → 8,000 tokens, $0.24 reviewer (gpt-4o-mini) → 3,000 tokens, $0.01 ``` # Google Gemini Source: https://docs.meshai.dev/framework-guides/gemini Auto-track all Google Gemini API calls ## Installation ```bash theme={null} pip install meshai-sdk[gemini] ``` ## Usage ```python theme={null} from meshai import MeshAI from meshai.integrations.gemini import wrap_gemini from google import genai client = MeshAI(api_key="msh_...", agent_name="my-agent") client.register(framework="custom", model_provider="google") # Wrap the Gemini client gem = wrap_gemini(genai.Client(), meshai=client) # Use as normal, all calls auto-tracked response = gem.models.generate_content( model="gemini-2.0-flash", contents="Hello", ) # Model, input/output tokens captured automatically # Works with different models too: response = gem.models.generate_content( model="gemini-2.5-pro", contents="Explain AI governance", ) ``` ## How It Works `wrap_gemini` wraps the Google Gen AI client's `generate_content` method. After each call, it: 1. Extracts the **model name** from the response `usage_metadata` 2. Extracts **input and output token counts** from `usage_metadata` 3. Sends the usage event to MeshAI (buffered, non-blocking) Works with both the new unified `google-genai` SDK and the legacy `google-generativeai` SDK. ## Alternative: Proxy (Zero-Code) There is no dedicated Gemini proxy route. Gemini traffic can be routed through the proxy's Vertex AI provider instead, using the Vertex path format, which requires the location and project in the URL: ``` https://proxy.meshai.dev/v1/vertex/k/msh_YOUR_PROXY_KEY/{location}/{project}/publishers/google/models/{model}:generateContent ``` For example: ``` https://proxy.meshai.dev/v1/vertex/k/msh_YOUR_PROXY_KEY/us-central1/my-project/publishers/google/models/gemini-2.0-flash:generateContent ``` This requires a Vertex AI project and Google Cloud credentials (a bearer token from ADC or a service account), not a plain Gemini API key. # LangChain / LangGraph Source: https://docs.meshai.dev/framework-guides/langchain Auto-track LLM calls in LangChain chains and LangGraph agents ## Installation ```bash theme={null} pip install meshai-sdk[langchain] ``` ## Usage with LangChain ```python theme={null} from meshai import MeshAI from meshai.integrations.langchain import MeshAICallbackHandler from langchain_openai import ChatOpenAI client = MeshAI(api_key="msh_...", agent_name="my-chain") client.register(framework="langchain") handler = MeshAICallbackHandler(client) # Pass to any LangChain model llm = ChatOpenAI(model="gpt-4o", callbacks=[handler]) response = llm.invoke("What is MeshAI?") # Model and tokens tracked automatically ``` ## Usage with LangGraph ```python theme={null} from langgraph.graph import StateGraph from meshai.integrations.langchain import MeshAICallbackHandler handler = MeshAICallbackHandler(client) # Pass as config to graph execution config = {"callbacks": [handler]} result = graph.stream(input_data, config=config) ``` ## Usage with Chains ```python theme={null} from langchain_core.prompts import ChatPromptTemplate prompt = ChatPromptTemplate.from_messages([...]) chain = prompt | llm # llm already has the handler from callbacks=[handler] result = chain.invoke({"topic": "AI governance"}) ``` ## How It Works `MeshAICallbackHandler` implements LangChain's callback interface. The `on_llm_end` method: 1. Extracts the **model name** from `LLMResult.llm_output` 2. Extracts **token usage** from the response metadata 3. Infers the **provider** from the model name 4. Sends to MeshAI (buffered, non-blocking) Works with any LangChain-compatible model: ChatOpenAI, ChatAnthropic, ChatGoogle, etc. # LlamaIndex Source: https://docs.meshai.dev/framework-guides/llamaindex Auto-track LLM calls in LlamaIndex pipelines ## Installation ```bash theme={null} pip install meshai-sdk[llamaindex] ``` ## Usage ```python theme={null} from meshai import MeshAI from meshai.integrations.llamaindex import MeshAILlamaHandler from llama_index.core import Settings, VectorStoreIndex from llama_index.core.callbacks import CallbackManager client = MeshAI(api_key="msh_...", agent_name="my-index") client.register(framework="llamaindex") # Add to the global callback manager handler = MeshAILlamaHandler(client) Settings.callback_manager = CallbackManager([handler]) # Use LlamaIndex as normal, all LLM calls tracked index = VectorStoreIndex.from_documents(documents) query_engine = index.as_query_engine() response = query_engine.query("What is MeshAI?") # Model and tokens captured automatically ``` ## How It Works `MeshAILlamaHandler` implements LlamaIndex's callback interface, listening to LLM events. On each LLM completion, it: 1. Extracts the **model name** from the LLM event payload 2. Extracts **input and output token counts** from the event callback data 3. Infers the **provider** from the model name 4. Sends the usage event to MeshAI (buffered, non-blocking) Works with any LlamaIndex-compatible LLM: OpenAI, Anthropic, Gemini, HuggingFace, and others. ## Alternative: Proxy (Zero-Code) If your LlamaIndex pipeline uses OpenAI or Anthropic, you can route through the proxy instead: ```bash theme={null} export OPENAI_BASE_URL=https://proxy.meshai.dev/v1/openai/k/msh_YOUR_PROXY_KEY ``` # OpenAI Source: https://docs.meshai.dev/framework-guides/openai Auto-track all OpenAI API calls ## Installation ```bash theme={null} pip install meshai-sdk[openai] ``` ## Usage ```python theme={null} from meshai import MeshAI from meshai.integrations.openai import wrap_openai import openai # Initialize MeshAI client = MeshAI(api_key="msh_...", agent_name="my-agent") client.register(framework="custom", model_provider="openai") # Wrap the OpenAI client oai = wrap_openai(openai.OpenAI(), meshai=client) # Use as normal, all calls auto-tracked response = oai.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Hello"}], ) # Model, tokens, and cost are captured automatically # Even when switching models: response = oai.chat.completions.create( model="gpt-4o-mini", # Different model, tracked separately messages=[{"role": "user", "content": "Hello"}], ) ``` ## What's Tracked For each API call, MeshAI captures: * **Model name** (extracted from the response, not hardcoded) * **Input tokens** (prompt\_tokens) * **Output tokens** (completion\_tokens) * **Request type** (chat.completions) ## Alternative: Proxy (Zero-Code) If you prefer no SDK at all: ```bash theme={null} export OPENAI_BASE_URL=https://proxy.meshai.dev/v1/openai/k/msh_YOUR_PROXY_KEY ``` All OpenAI calls are automatically routed through MeshAI. # Pydantic AI Source: https://docs.meshai.dev/framework-guides/pydantic-ai Auto-track LLM calls in Pydantic AI agents ## Installation ```bash theme={null} pip install meshai-sdk[pydantic-ai] ``` ## Usage ```python theme={null} from meshai import MeshAI from meshai.integrations.pydantic_ai import track_pydantic_ai from pydantic_ai import Agent client = MeshAI(api_key="msh_...", agent_name="my-pydantic-agent") client.register(framework="pydantic-ai") # Enable global tracking track_pydantic_ai(client) # Run your agents as normal agent = Agent("openai:gpt-4o", system_prompt="You are a helpful assistant") # Both async and sync are tracked result = agent.run_sync("What is AI governance?") print(result.data) # Model and tokens tracked automatically ``` ## How It Works `track_pydantic_ai` patches `Agent.run` and `Agent.run_sync` to intercept LLM calls. After each agent run, it: 1. Extracts the **model name** from the agent's model configuration 2. Extracts **token counts** from `RunResult.usage()` (`RunUsage` object) 3. Infers the **provider** from the model string prefix 4. Sends the usage event to MeshAI (buffered, non-blocking) Works with all Pydantic AI-supported models: OpenAI, Anthropic, Gemini, Groq, Mistral, and others. ## Alternative: Proxy (Zero-Code) If your Pydantic AI agents use OpenAI or Anthropic, route through the proxy: ```bash theme={null} export OPENAI_BASE_URL=https://proxy.meshai.dev/v1/openai/k/msh_YOUR_PROXY_KEY ``` # Semantic Kernel Source: https://docs.meshai.dev/framework-guides/semantic-kernel Auto-track LLM calls in Microsoft Semantic Kernel ## Installation ```bash theme={null} pip install meshai-sdk[semantic-kernel] ``` ## Usage ### Option 1: Global Tracking ```python theme={null} from meshai import MeshAI from meshai.integrations.semantic_kernel import track_semantic_kernel from semantic_kernel import Kernel client = MeshAI(api_key="msh_...", agent_name="my-sk-agent") client.register(framework="semantic-kernel") kernel = Kernel() # ... add AI services to kernel ... # Enable tracking on the kernel track_semantic_kernel(client, kernel) # Use as normal, all LLM calls tracked result = await kernel.invoke(my_function, input="Hello") ``` ### Option 2: Prompt Filter ```python theme={null} from meshai.integrations.semantic_kernel import MeshAIPromptFilter from semantic_kernel import Kernel kernel = Kernel() # ... add AI services to kernel ... # Add as a prompt filter kernel.add_filter("prompt", MeshAIPromptFilter(client)) result = await kernel.invoke(my_function, input="Hello") # Model and tokens tracked automatically ``` ## How It Works MeshAI integrates via Semantic Kernel's function invocation filter system. The `MeshAIPromptFilter` intercepts prompt render and completion events: 1. Extracts the **model name** from the AI service configuration 2. Extracts **token counts** from the completion result metadata 3. Infers the **provider** from the model or service type 4. Sends the usage event to MeshAI (buffered, non-blocking) Works with all Semantic Kernel AI connectors: OpenAI, Azure OpenAI, Google, HuggingFace, and others. ## Alternative: Proxy (Zero-Code) If your Semantic Kernel uses OpenAI or Azure OpenAI, route through the proxy: ```bash theme={null} export OPENAI_BASE_URL=https://proxy.meshai.dev/v1/openai/k/msh_YOUR_PROXY_KEY ``` # Claude Code Connector Source: https://docs.meshai.dev/getting-started/claude-code Durable, evidence-grade telemetry for Claude Code, built for EU AI Act Article 12 # meshai-claude-code EU AI Act Article 12 requires durable records of AI system activity, not best-effort logs. Best-effort telemetry loses events exactly when it matters most: process crashes, OOM kills, network outages. The `meshai-claude-code` connector fsyncs every hook event to a local write-ahead log before anything else happens, so a crash cannot lose an acknowledged event. Only disk failure can. ## Install ```bash theme={null} pipx install meshai-claude-code ``` The current release is `0.2.1` and requires `meshai-sdk[tracer]>=0.6.0`. Upgrade an existing pipx installation with: ```bash theme={null} pipx upgrade meshai-claude-code ``` This dependency update does not enable prompt capture. The connector remains metadata-only by default, and its existing per-tool content allowlist is separate from SDK GenAI input capture. Plain `pip install` inside a virtual environment also works. On a system Python, bare `pip install` fails with `error: externally-managed-environment` (PEP 668) on modern Debian, Ubuntu, and Homebrew. Use pipx, a venv, or `pip install --break-system-packages` if you understand the tradeoff. ## Setup ```bash theme={null} meshai-claude-code login --api-key msh_... ``` ```bash theme={null} meshai-claude-code install ``` Registers the connector's hooks in `~/.claude/settings.json`, with a backup of your existing settings and a clean uninstall path. The daemon starts automatically on your next Claude Code session (`auto_start_daemon: true` by default), or you can run it directly with `meshai-cc-daemon`. ```bash theme={null} meshai-claude-code status ``` ## Architecture ``` fsync tail OTLP POST ┌──────┐ event ┌──────┐ nudge ┌────────┐ ┌────────────┐ │ hook │───────▶│ WAL │◀───────────│ daemon │────────▶│ MeshAI API │ └──────┘ └──────┘ └────┬───┘ └────────────┘ 1s poll backstop ``` * **Hooks** run on SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, and Stop. Each hook appends a CRC-framed record to the WAL with a real fsync and exits. * **The WAL** (write-ahead log) is local, durable state. Hooks own writes; the daemon only reads. * **The daemon** converts WAL events to OpenTelemetry spans and exports them to MeshAI over OTLP. Delivery is at-least-once; span IDs are minted once at hook time, so MeshAI's ingest dedup makes accounting exactly-once. ## Content filtering Tool content (`tool_input` / `tool_output`) is dropped by default. Structural metadata (event type, tool name, timing, token counts) always flows. Opt in per tool in `~/.config/meshai/filters.yaml`: ```yaml theme={null} tools: Bash: allow: [tool_input] ``` Allowlisted content passes through the MeshAI SDK's secret-redaction pipeline before it leaves your machine, and fails closed on any doubt. ## Compliance mode ```yaml theme={null} # ~/.config/meshai/policy.yaml fail_closed: true # WAL append failure blocks Claude Code agent_name: my-cc # registry identity; default claude-code- base_url: https://api.meshai.dev ``` With `fail_closed: true`, a tool call that cannot be durably recorded does not run: no evidence means no action. ## Platforms macOS, Linux, and WSL (v1). On WSL, state must live on the Linux filesystem, not `/mnt/c`; this is the default (`~/.local/state/meshai-cc`). Native Windows support is planned for v2. ## Source Apache-2.0. Source at [github.com/meshailabs-org/meshai-claude-code](https://github.com/meshailabs-org/meshai-claude-code). # Codex CLI Connector Source: https://docs.meshai.dev/getting-started/codex Zero-code telemetry from OpenAI Codex CLI's built-in OpenTelemetry exporter # Codex CLI OpenAI Codex CLI ships a built-in OpenTelemetry exporter. Point it at MeshAI's OTLP logs endpoint and every Codex session is monitored with no package to install: per-turn token usage and cost, tool approval decisions, sandbox outcomes, and session activity. ## Configure Add an `[otel]` block to `~/.codex/config.toml`: ```toml theme={null} [otel] environment = "prod" log_user_prompt = false # default; prompts leave the machine as "[REDACTED]" [otel.exporter.otlp-http] endpoint = "https://api.meshai.dev/api/v1/ingest/v1/logs" protocol = "json" [otel.exporter.otlp-http.headers] authorization = "Bearer msh_YOUR_API_KEY" ``` Use an API key with the `telemetry:write` scope. The next Codex session (interactive or `codex exec`) starts exporting; the agent appears in your MeshAI registry within about a minute as `codex_exec` or `codex_tui`, framework `codex`, with each Codex conversation tracked as a session. The API key sits in plaintext in `config.toml`, so keep the file `chmod 600` and use a key scoped to `telemetry:write` only. Codex has no environment-variable indirection for exporter headers yet. ## What's tracked | Codex event | Becomes | | -------------------------------------- | ------------------------------------------------------- | | `codex.sse_event` (turn completed) | Token usage and cost row: input, output, model, session | | `codex.tool_decision` | Activity: tool name and approve/deny decision | | `codex.sandbox_outcome` | Activity: sandbox escalations and outcomes | | `codex.user_prompt`, connection events | Activity and session liveness | ## Privacy Only usage, model, and session metadata is persisted. MeshAI's ingest maps Codex events onto OpenTelemetry GenAI semantic conventions at the boundary and drops everything else: prompts (already `[REDACTED]` by Codex unless you opt in), `user.email`, and auth diagnostics never reach storage. Leave `log_user_prompt = false`; the Codex log integration does not use prompt text. ## Durability caveat Codex's exporter is in-process and fire-and-forget: events buffered when the process crashes or the network is down are lost. That is fine for monitoring and cost attribution. If you need evidence-grade capture with a local write-ahead log, that is what the [Claude Code connector](/getting-started/claude-code) provides for Claude Code; a durable Codex connector is on the roadmap. ## Requirements Codex CLI 0.146 or later (earlier versions with the `[otel]` config section also work; telemetry verified against 0.147). # Core Concepts Source: https://docs.meshai.dev/getting-started/concepts Key concepts in the MeshAI Agent Control Plane ## Tenant A tenant is your organization in MeshAI. All data is isolated per tenant. Agents, policies, audit events, and billing are scoped to your tenant. ## Agent An AI agent registered in MeshAI. Each agent has: * **Name** and **description** * **Framework** (CrewAI, LangChain, AutoGen, custom) * **Model provider** and **model name** * **Environment** (production, staging, dev) * **Status** (healthy, degraded, down, unknown) ## API Key Bearer token (`msh_...`) used to authenticate with the MeshAI API. Two types: * **Admin keys**: full access (manage agents, policies, billing) * **Proxy keys**: forward-only access (route LLM requests through the proxy) ## Policy A governance rule enforced in real-time through the proxy. Eight types: * `model_allowlist`: restrict which models agents can use * `block_provider`: block specific LLM providers * `require_approval`: require human approval (HITL) * `budget_limit`: enforce monthly spend limits * `rate_limit`: additional request throttling * `require_human_review`: flag for periodic review * `prompt_injection` - detect and block prompt injection attempts * `pii_filter` - detect and redact PII in requests or responses ## Risk Classification EU AI Act risk level assigned to each agent: * **Minimal**: low risk, basic monitoring * **Limited**: transparency obligations * **High**: full compliance required (audit trail, HITL, FRIA) * **Unacceptable**: should not be deployed without safeguards ## Audit Event Immutable log entry recording a governance action (agent registered, anomaly acknowledged, policy created, approval decided). Required by EU AI Act Article 12. ## Readiness Score Compliance score (0-120) across 7 components measuring your organization's EU AI Act readiness. # FAQ Source: https://docs.meshai.dev/getting-started/faq Frequently asked questions about MeshAI ## General MeshAI is the Agent Control Plane, the only platform that monitors AND governs AI agents. It provides unified observability, governance, cost intelligence, and EU AI Act compliance for enterprise AI agent deployments, regardless of framework or vendor. Those tools focus on observability: tracing, debugging, evals. MeshAI does observability **plus** governance: 8 policy types, with inline enforcement for allowlists, provider blocks, and human approval at the proxy, kill switch, agent quarantine, prompt injection detection, PII filtering, and EU AI Act compliance scoring. Nobody else combines monitoring and governance in one platform. No. The MeshAI proxy works with one environment variable change, zero code modifications. Set `ANTHROPIC_BASE_URL` or `OPENAI_BASE_URL` to point at the proxy and you're monitoring instantly. For deeper integration, our Python SDK supports 11 frameworks. OpenAI, Anthropic, CrewAI, LangChain/LangGraph, AutoGen, Google Gemini, AWS Bedrock, LlamaIndex, Agno (ex-Phidata), Pydantic AI, and Microsoft Semantic Kernel. Platform integrations for enterprise tools like Copilot Studio, Salesforce Einstein, and ServiceNow are on the roadmap; today MeshAI covers custom agents built on any framework through the SDK, OpenTelemetry, or the proxy. Anthropic (Claude), OpenAI (GPT, o1), Google Gemini (via the Vertex AI route), AWS Bedrock, NVIDIA Nemotron, all through the transparent proxy with zero code changes. ## EU AI Act & Compliance **Yes.** The EU AI Act has extraterritorial reach, the same as GDPR. If your non-EU company's AI system reaches the EU market or its outputs are used by EU residents, the Act applies. Any company outside the EU, whether based in the US, UK, Asia, or elsewhere, using AI agents for EU customer support, hiring, or financial services must comply. High-risk (Annex III) obligations are postponed to December 2, 2027 under the 2026 Digital Omnibus; prohibited practices (in effect since February 2025), general-purpose AI model obligations (since August 2025), and the Act's transparency obligations (enforcement began August 2, 2026) apply today. Fines are based on **global** turnover, not just EU revenue. You're classified as a **deployer** under the EU AI Act (Article 26). Even though the AI is from a third party, you can't shift responsibility to the provider. If your service uses AI (e.g., speech-to-text, chatbots, content generation) and EU residents consume the output, you must comply. This includes maintaining audit trails, informing users they're interacting with AI, and classifying the risk level of your AI systems. MeshAI automates all of this. The Act defines 6 roles: * **Provider**: develops the AI system and places it on the market (e.g., OpenAI, Anthropic, Google). Must do conformity assessments, technical documentation, CE marking, and post-market monitoring. * **Deployer**: uses an AI system in their business (e.g., a SaaS company using GPT for customer support). Must ensure human oversight, maintain logs, inform users, and classify risk. **This is MeshAI's primary customer.** * **Importer**: brings non-EU AI systems into the EU market. Must verify CE marking and conformity documentation. * **Distributor**: makes AI systems available within the EU without modifying them (e.g., cloud marketplaces). Must verify compliance before selling. * **Authorized Representative**: EU-based entity acting on behalf of a non-EU provider. * **Product Manufacturer**: integrates AI into a physical product (e.g., autonomous vehicles). Same obligations as provider for the AI component. **Important:** If a deployer modifies the AI system's intended purpose or makes substantial changes, they become reclassified as a **provider** under Article 25, inheriting all provider obligations. * **Prohibited AI practices**: up to 35 million or 7% of global annual turnover * **High-risk AI obligations** (Articles 26, 27): up to 15 million or 3% of global turnover * **Incorrect information to authorities**: up to 7.5 million or 1.5% of global turnover For SMEs and startups, fines are the **lower** of the percentage and fixed amount (not the higher). MeshAI provides tooling for 8 articles: * **Article 6**: Risk classification (4 levels with AI-assisted suggestion) * **Article 12**: Record-keeping (immutable audit trail, 6-month retention, CSV/JSON export) * **Article 13**: Transparency (auto-generated transparency cards) * **Article 14**: Human oversight (HITL approval workflows) * **Article 26**: Deployer obligations (12 obligations covered) * **Article 27**: FRIA with all 6 required fields (a-f) * **Article 50**: Transparency obligations * **Article 73**: Serious incident reporting (15-day/2-day deadlines) Article 27 requires deployers of high-risk AI systems to assess impacts on fundamental rights before deployment. MeshAI provides structured FRIA templates with all 6 required fields: intended purpose, usage period/frequency, affected person categories, specific risks, human oversight measures, and risk mitigation measures. FRIAs are versioned and can be submitted for authority notification. MeshAI computes a 0-120 score across 7 components: audit trail active (Art 12), risk classification coverage (Art 6), human oversight for high-risk agents (Art 14), documentation completeness (Art 11), data retention (Art 12), FRIA completion (Art 27), and incident response (Art 73). Target: 100+ for enforcement readiness. Enforcement of the Act began **August 2, 2026**: prohibited practices (in effect since February 2025), general-purpose AI model obligations (August 2025), and transparency obligations are enforceable now, with national authorities and complaint channels active. High-risk AI system obligations (Articles 26, 27, Annex III) are postponed to **December 2, 2027** under the 2026 Digital Omnibus. ## Security & Privacy By default, payload capture is off and MeshAI persists operational metadata rather than prompt or completion content. A tenant can explicitly enable bounded, pattern-sanitized **input-only** capture for supported proxy requests and OpenTelemetry attributes. Mandatory and tenant-defined redaction runs before storage, but sanitized data is not necessarily anonymous or PII-free. Each record becomes eligible for scheduled deletion according to its captured retention setting. Provider outputs and completions are never captured by this feature. See [Sanitized Input Capture](/governance/payload-capture). All data is encrypted at rest (AES-256) and in transit (TLS 1.2+ on all connections). API keys are hashed with bcrypt, never stored in plaintext. Provider API keys can be stored in AWS Secrets Manager with only reference pointers in the database. Yes. Every database query includes tenant-scoped filtering. Cross-tenant data access is architecturally impossible through the API. Each customer's agents, policies, audit events, and billing are completely isolated. MeshAI scans all request bodies at the proxy layer for 15+ known injection patterns including instruction override, system prompt extraction, role hijacking, delimiter attacks, and encoding evasion. Patterns are normalized with Unicode NFKC to prevent homoglyph bypasses. Detected injections return 403 before reaching the LLM provider. MeshAI can detect PII in LLM responses (emails, phone numbers, SSNs, credit cards, IPs, passports, IBANs) and apply one of three actions per your policy: * **Block**: return 403, don't forward the response * **Redact**: replace PII with `[EMAIL_REDACTED]`, `[SSN_REDACTED]` etc. * **Allow**: log the detection but return the response unchanged You choose the mode based on your use case. Agents that need PII (e.g., customer support) can use "allow" mode. The proxy is designed to fail gracefully. If MeshAI is unavailable, configure your agents to fall back to direct provider URLs. The proxy itself runs on Cloud Run with auto-scaling (2-50 instances) and adds less than 5ms latency. Governance policies fail open on Redis errors. Your agents keep working. ## Pricing & Plans * **Starter**: \$299/month, up to 25 agents * **Professional**: \$799/month, up to 100 agents * **Enterprise**: \$1,999/month, up to 1,000 agents * **Enterprise Plus**: Custom pricing, unlimited agents, dedicated infrastructure All plans include the proxy, dashboard, SDK, and governance features. We're offering free Professional tier (3 months) for early beta users. [Contact us](https://meshai.dev/contact) or [join the waitlist](https://meshai.dev/#waitlist). You won't be able to register new agents until you upgrade or remove existing ones. Existing agents continue to work. We never block running agents due to billing limits. Enterprise Plus plans support annual contracts with invoicing. Contact sales for details. ## Technical Less than 5ms. The proxy evaluates governance policies locally from Redis cache and forwards requests to the upstream provider. Telemetry is fire-and-forget (async, non-blocking). When you block an agent, a flag is set in both PostgreSQL and Redis. The proxy checks Redis on every request. Blocked agents get an instant 403 response. No waiting for cache expiry. Unblocking is equally instant. **Kill switch**: immediate block for a known agent that's behaving badly. Admin action. **Quarantine**: isolation for unknown or suspicious agents. Can be auto-triggered when the proxy detects an unregistered agent. Both result in a 403 at the proxy, but quarantine implies investigation is needed before release. Yes. MeshAI focuses on AI agent governance. It complements Datadog, Grafana, PagerDuty, etc. We integrate with PagerDuty and Slack for alerting, and the audit trail can be exported as CSV/JSON for ingestion into any SIEM or compliance tool. The Python SDK (`meshai-sdk`) is MIT licensed and available on PyPI and GitHub. The platform (API, proxy, dashboard) is proprietary. Currently the SDK is Python-only. However, the proxy requires no SDK. Any language that can set an environment variable works. JavaScript, Go, Rust, Java agents all work through the proxy with zero code changes. **Yes**, two integration paths: **Path 1: Proxy (tools with custom base URL support)** * **Claude Code**: `ANTHROPIC_BASE_URL=https://proxy.meshai.dev/v1/anthropic/k/msh_KEY` * **Cursor**: Settings → Models → Custom Base URL * **Cline / Roo Code**: Settings → API Base URL * **Codex**: `OPENAI_BASE_URL=https://proxy.meshai.dev/v1/openai/k/msh_KEY` **Path 2: MCP Server (tools without proxy support)** No install needed. Configure `npx -y @meshailabs/mcp-server` in your tool's MCP settings. Supports **19+ tools**: Claude Desktop, VS Code Copilot, JetBrains IDEs, Windsurf, Zed, Warp, AWS Kiro, Continue.dev, Amazon Q Developer, Gemini CLI, Tabnine, Goose, and more. The MCP server registers the tool as a governed agent, tracks usage, checks policies, and reports compliance, all without proxying traffic. See the [MCP Server guide](/getting-started/mcp-server) for setup instructions per tool. # Introduction Source: https://docs.meshai.dev/getting-started/introduction MeshAI is the Agent Control Plane: see, govern, and comply # What is MeshAI? MeshAI provides unified **observability**, **governance**, and **cost intelligence** for enterprise AI agent deployments. It discovers, monitors, and governs all AI agents across your organization, regardless of framework or vendor. ## The Problem Organizations are deploying AI agents faster than they can track them. This creates: * **Agent sprawl**: 144:1 non-human identities per employee, most ungoverned * **Reliability gaps**: 20-step agent chains have only \~36% end-to-end reliability * **Cost opacity**: Token spend is invisible and unattributed across teams * **Compliance risk**: EU AI Act enforcement began August 2, 2026 (prohibited practices, transparency, GPAI rules); Annex III high-risk obligations deferred to December 2, 2027 under the Digital Omnibus; audit-ready evidence still needs 12+ months of history ## Four Pillars Auto-discover all AI agents. Detect shadow agents, maintain a living inventory, monitor health in real time. Four detection algorithms evaluate cost spikes, reliability decay, behavioral drift, and security threats on a live five-minute production schedule. Expanded OTLP error and duration analysis was activated through API PR #84 on August 11, 2026. Token-level spend attribution by team, project, and agent. Budget guardrails with automatic enforcement. Eight policy types enforced in real-time. HITL approval workflows. [Oversight metrics](/governance/oversight-metrics) and incident evidence packs prove human oversight is real, not decorative. [Agent-to-agent delegation mapping](/governance/relationships) traces multi-agent chains. EU AI Act readiness scoring. ## Three Ways to Connect One env var change. All LLM requests flow through MeshAI's transparent proxy for automatic monitoring. Python SDK with auto-tracking for [11 frameworks](/framework-guides/openai): OpenAI, Anthropic, CrewAI, LangChain, AutoGen, and more. Governance and observability for MCP-compatible tools that don't support a custom base URL, like Claude Desktop, VS Code, and JetBrains IDEs. Using **Claude Code**? See the [Claude Code connector](/getting-started/claude-code) for durable, crash-proof telemetry backed by a local write-ahead log. # MCP Server Source: https://docs.meshai.dev/getting-started/mcp-server Governance and observability for Claude Desktop, VS Code, JetBrains, Cursor, Windsurf, Zed, Warp, and 10+ more tools # MeshAI MCP Server The MeshAI MCP Server brings governance and observability to **any MCP-compatible AI tool**, even tools that don't support custom API base URLs. ## When to Use | Integration Path | Best For | | --------------------- | ------------------------------------------------------------------------------------- | | **MeshAI Proxy** | Tools with custom base URL support (Claude Code, Cursor, Cline, Codex) | | **MeshAI MCP Server** | Tools without proxy support (Claude Desktop, VS Code, JetBrains, Windsurf, Zed, Warp) | | **Both** | Maximum coverage: proxy for traffic monitoring, MCP for governance tools | ## Setup No global install needed. Each tool config uses `npx` to download `@meshailabs/mcp-server` from the npm registry and run the prebuilt package. ## Environment Variables | Variable | Required | Default | Description | | ------------------- | -------- | ------------------------ | ----------------------------------- | | `MESHAI_API_KEY` | Yes | - | Your MeshAI API key (`msh_...`) | | `MESHAI_API_URL` | No | `https://api.meshai.dev` | API endpoint | | `MESHAI_AGENT_NAME` | No | `mcp-agent` | Name for this agent in the registry | ## Configuration by Tool ### Claude Desktop Edit `~/Library/Application Support/Claude/claude_desktop_config.json` (Mac) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows): ```json theme={null} { "mcpServers": { "meshai": { "command": "npx", "args": ["-y", "@meshailabs/mcp-server"], "env": { "MESHAI_API_KEY": "msh_your_key_here", "MESHAI_AGENT_NAME": "claude-desktop" } } } } ``` ### Cursor Add to `.cursor/mcp.json` or Settings > MCP Servers: ```json theme={null} { "meshai": { "command": "npx", "args": ["-y", "@meshailabs/mcp-server"], "env": { "MESHAI_API_KEY": "msh_your_key_here", "MESHAI_AGENT_NAME": "cursor" } } } ``` ### Windsurf Edit `~/.codeium/windsurf/mcp_config.json`: ```json theme={null} { "mcpServers": { "meshai": { "command": "npx", "args": ["-y", "@meshailabs/mcp-server"], "env": { "MESHAI_API_KEY": "msh_your_key_here", "MESHAI_AGENT_NAME": "windsurf" } } } } ``` ### VS Code (GitHub Copilot) Add to `.vscode/mcp.json`: ```json theme={null} { "servers": { "meshai": { "command": "npx", "args": ["-y", "@meshailabs/mcp-server"], "env": { "MESHAI_API_KEY": "msh_your_key_here", "MESHAI_AGENT_NAME": "vscode" } } } } ``` ### JetBrains IDEs **Settings > Tools > AI Assistant > Model Context Protocol (MCP) > Add Server:** * Command: `npx` * Args: `-y @meshailabs/mcp-server` * Environment: `MESHAI_API_KEY=msh_your_key_here`, `MESHAI_AGENT_NAME=jetbrains` Works with IntelliJ IDEA, PyCharm, WebStorm, GoLand, Rider, and all other JetBrains IDEs. ### Zed Add to `~/.config/zed/settings.json`: ```json theme={null} { "context_servers": { "meshai": { "source": "custom", "command": { "path": "npx", "args": ["-y", "@meshailabs/mcp-server"] }, "env": { "MESHAI_API_KEY": "msh_your_key_here", "MESHAI_AGENT_NAME": "zed" } } } } ``` ### Warp **Settings > Agent > MCP > Add Server:** * Command: `npx` * Args: `-y @meshailabs/mcp-server` * Environment: `MESHAI_API_KEY=msh_your_key_here`, `MESHAI_AGENT_NAME=warp` ### AWS Kiro Add to `.kiro/mcp.json`: ```json theme={null} { "mcpServers": { "meshai": { "command": "npx", "args": ["-y", "@meshailabs/mcp-server"], "env": { "MESHAI_API_KEY": "msh_your_key_here", "MESHAI_AGENT_NAME": "kiro" } } } } ``` ### Cline / Roo Code / Kilo Code **Settings > MCP Servers > Add Server:** * Command: `npx` * Args: `-y @meshailabs/mcp-server` * Environment: `MESHAI_API_KEY=msh_your_key_here`, `MESHAI_AGENT_NAME=cline` ### Continue.dev Add to `~/.continue/config.yaml`: ```yaml theme={null} mcpServers: - name: meshai command: npx args: - "-y" - "@meshailabs/mcp-server" env: MESHAI_API_KEY: msh_your_key_here MESHAI_AGENT_NAME: continue ``` ### Amazon Q Developer Add to `~/.aws/amazonq/mcp.json`: ```json theme={null} { "mcpServers": { "meshai": { "command": "npx", "args": ["-y", "@meshailabs/mcp-server"], "env": { "MESHAI_API_KEY": "msh_your_key_here", "MESHAI_AGENT_NAME": "amazon-q" } } } } ``` ### Gemini CLI Add to `~/.gemini/settings.json`: ```json theme={null} { "mcpServers": { "meshai": { "command": "npx", "args": ["-y", "@meshailabs/mcp-server"], "env": { "MESHAI_API_KEY": "msh_your_key_here", "MESHAI_AGENT_NAME": "gemini-cli" } } } } ``` ### Sourcegraph Cody / Tabnine / Goose These tools follow similar MCP configuration patterns. Set: * Command: `npx` * Args: `-y @meshailabs/mcp-server` * Environment: `MESHAI_API_KEY=msh_your_key_here`, `MESHAI_AGENT_NAME=` Refer to each tool's MCP documentation for the exact config file location. ## Available Tools Once configured, the MCP server exposes 8 tools to the AI assistant: | Tool | Description | | ------------------------ | ------------------------------------------------ | | `meshai_register` | Register this tool as a governed agent in MeshAI | | `meshai_heartbeat` | Send health heartbeat for uptime monitoring | | `meshai_track_usage` | Report token usage for cost tracking | | `meshai_check_policy` | Check if a model/provider is allowed before use | | `meshai_get_risk` | Get EU AI Act risk classification | | `meshai_get_compliance` | Get compliance readiness score (0-120) | | `meshai_report_incident` | Report a security incident (Article 73) | | `meshai_audit_log` | Query the governance audit trail | ## Available Resources | URI | Description | | ------------------------------ | --------------------------------- | | `meshai://agent/status` | Current agent status and metadata | | `meshai://governance/policies` | Active governance policies | | `meshai://compliance/score` | EU AI Act readiness score | ## How It Works 1. Your AI tool (e.g., Claude Desktop) starts the MeshAI MCP server via `npx` 2. `npx` downloads the prebuilt package from the npm registry and runs it as a subprocess 3. The server connects to the MeshAI API using your API key 4. The AI tool can call MeshAI governance tools alongside its normal capabilities 5. The MeshAI dashboard shows this tool alongside all other agents 6. Governance policies, audit trails, and compliance features apply universally ## Supported Tools | Tool | MCP Support | Proxy Support | MCP Server Fills Gap? | | ------------------ | ----------- | ------------- | --------------------- | | Claude Desktop | Yes | No | **Yes** | | Claude Code | Yes | Yes | Optional | | Cursor | Yes | Yes | Optional | | Windsurf | Yes | Partial | **Yes** | | Cline | Yes | Yes | Optional | | Roo Code | Yes | Yes | Optional | | Kilo Code | Yes | Yes | Optional | | AWS Kiro | Yes | TBD | **Yes** | | VS Code Copilot | Yes | No | **Yes** | | JetBrains IDEs | Yes | No | **Yes** | | Zed | Yes | No | **Yes** | | Warp | Yes | No | **Yes** | | Continue.dev | Yes | Yes | Optional | | Sourcegraph Cody | Yes | Yes | Optional | | Tabnine | Yes | No | **Yes** | | Amazon Q Developer | Yes | No | **Yes** | | Gemini CLI | Yes | No | **Yes** | | Goose | Yes | No | **Yes** | | Codex | Yes | Yes | Optional | > **"MCP Server Fills Gap?"**: **Yes** means the tool has no custom base URL support, so the MCP server is the only way to get MeshAI governance. **Optional** means the tool already supports the proxy; the MCP server adds governance tools but isn't required. # OpenTelemetry Ingestion Source: https://docs.meshai.dev/getting-started/opentelemetry Send traces, metrics, and logs from any OTLP-compatible agent to MeshAI MeshAI accepts standard [OTLP/HTTP](https://opentelemetry.io/docs/specs/otlp/#otlphttp) exports. Point any OpenTelemetry-instrumented agent at MeshAI and it will auto-discover agents, persist span activity, extract token usage when present, and populate the registry automatically. ## Endpoints | Endpoint | Host | Method | Description | | --------------------------- | ------------------- | ------ | --------------------------------------------------------------------------- | | `/api/v1/ingest/v1/traces` | `ingest.meshai.dev` | POST | OTLP trace export (JSON) | | `/api/v1/ingest/v1/metrics` | `ingest.meshai.dev` | POST | OTLP metrics export (JSON, processing deferred) | | `/api/v1/ingest/v1/logs` | `api.meshai.dev` | POST | OTLP logs export, used by the [Codex CLI connector](/getting-started/codex) | All three require an API key with the `telemetry:write` scope. The host column is not decoration: see the note below on why logs differ. ## Quick Setup Set the standard OpenTelemetry environment variable to point at MeshAI: ```bash theme={null} export OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.meshai.dev/api/v1/ingest # Logs are served by api.meshai.dev, not the collector. Signal-specific # endpoints are used as-is, so this one carries the full path. export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://api.meshai.dev/api/v1/ingest/v1/logs export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer msh_YOUR_API_KEY" export OTEL_SERVICE_NAME=my-agent ``` Traces and metrics go to **`ingest.meshai.dev`**, a separate host from `api.meshai.dev`. That is deliberate, not a typo: ingest runs behind an OpenTelemetry collector that absorbs large exports and splits them into smaller batches, so a batch too big for the API in one piece is still recorded rather than rejected. Registry, cost and governance stay on `api.meshai.dev`. **Logs are the exception.** The collector is configured for traces and metrics only, so `/api/v1/ingest/v1/logs` is served directly by `api.meshai.dev`. Send logs to `ingest.meshai.dev` and you get a `404`, which is not in OTLP's retryable set, so the exporter drops the batch rather than holding it, with nothing to see server-side. That is why the Codex CLI connector points at `api.meshai.dev`. Do not infer a host from a status code here. An unauthenticated request is rejected at the edge before routing, so every path on `ingest.meshai.dev` answers `401` whether or not it exists. A `200` from the ingest endpoint means your batch was **accepted**, not yet stored, because the collector forwards it onward. A missing or malformed key returns `401` immediately, but an expired key or one lacking `telemetry:write` is only rejected further along. Confirm spans actually arrived in the dashboard rather than relying on the status code. That's it. Any OTLP-compatible SDK or agent will now export traces to MeshAI. The ingest endpoint accepts OTLP protobuf (`application/x-protobuf`, the stock OTLP SDK default), OTLP JSON, and gzip-compressed bodies (`Content-Encoding: gzip`). Set `OTEL_EXPORTER_OTLP_PROTOCOL=http/json` only if you need to force JSON. `OTEL_SERVICE_NAME` sets the `service.name` attribute MeshAI uses to name your auto-discovered agent. If you use a real OpenTelemetry SDK and leave it unset, the SDK itself injects a default of `unknown_service:` (for example `unknown_service:python`). If your OTLP payload omits the `service.name` resource attribute entirely, such as from a hand-rolled emitter that doesn't use an OTel SDK, MeshAI falls back to naming the agent `unknown-agent`. ## What Gets Extracted When MeshAI receives trace data, it automatically: 1. **Discovers agents** from the `service.name` resource attribute (set via `OTEL_SERVICE_NAME` or your SDK's `Resource`). Each distinct `service.name` becomes its own agent in the registry. On the free tier only one agent is admitted: the first `service.name` claims the single free slot and spans from any other `service.name` are dropped until you upgrade, so emit under one `service.name` on the free tier and split into per-service agents once on a paid plan 2. **Extracts token usage** from `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` attributes 3. **Records model info** from `gen_ai.request.model` and `gen_ai.system` attributes 4. **Records non-token activity** separately, so operational spans and failed calls without usage attributes still contribute activity and error evidence without appearing as billable usage 5. **Records bounded span duration samples** when valid start and end timestamps are present. Missing, malformed, zero, negative, or longer-than-24-hour durations are excluded from latency statistics without rejecting the span 6. **Registers new agents** in your registry if they don't already exist ## Python Example Using the OpenTelemetry Python SDK: ```python theme={null} from opentelemetry import trace from opentelemetry.sdk.resources import Resource from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter # Configure exporter to send to MeshAI exporter = OTLPSpanExporter( endpoint="https://ingest.meshai.dev/api/v1/ingest/v1/traces", headers={"Authorization": "Bearer msh_YOUR_API_KEY"}, ) provider = TracerProvider( resource=Resource.create({"service.name": "my-agent"}) ) provider.add_span_processor(BatchSpanProcessor(exporter)) trace.set_tracer_provider(provider) tracer = trace.get_tracer("my-agent") # Your agent code, spans are automatically exported with tracer.start_as_current_span("agent.run") as span: span.set_attribute("gen_ai.request.model", "gpt-4o") span.set_attribute("gen_ai.usage.input_tokens", 1500) span.set_attribute("gen_ai.usage.output_tokens", 800) # ... agent logic ... ``` ## Node.js Example ```javascript theme={null} const { OTLPTraceExporter } = require("@opentelemetry/exporter-trace-otlp-http"); const exporter = new OTLPTraceExporter({ url: "https://ingest.meshai.dev/api/v1/ingest/v1/traces", headers: { Authorization: "Bearer msh_YOUR_API_KEY" }, }); ``` ## Framework Integration Most agent frameworks support OpenTelemetry natively or via plugins: | Framework | OTel Support | | --------------- | ---------------------------------------------- | | LangChain | `langchain-opentelemetry` package | | CrewAI | Built-in `OTEL_EXPORTER_OTLP_ENDPOINT` support | | AutoGen | OpenTelemetry tracing via `autogen-ext` | | Semantic Kernel | Built-in `ActivitySource` (maps to OTel) | | Custom agents | Use any OTLP SDK | Set the environment variables above and these frameworks will export traces to MeshAI automatically. ## Response Format ```json theme={null} { "success": true, "data": { "accepted_spans": 12, "duplicate_spans": 0, "rejected_spans": 0, "agents_discovered": 1 } } ``` | Field | Description | | ------------------- | ------------------------------------------------------------------------------------ | | `accepted_spans` | Number of newly recorded spans, including token-bearing and non-token activity spans | | `duplicate_spans` | Number of replayed spans already recorded through at-least-once delivery | | `rejected_spans` | Number of spans that could not be admitted or persisted | | `agents_discovered` | Number of new agents auto-registered from this batch | A `200` can be returned when `accepted_spans` is `0`. Check `duplicate_spans`, `rejected_spans`, `rejected_reasons`, and any `partial_success` value rather than inferring the outcome from the status code alone. A span without `gen_ai.usage.*` is recorded as non-billable activity; add usage attributes when you also want cost and token accounting. ## Anomaly signal coverage Proxy and OTLP telemetry use separate reliability baselines. Both can contribute request counts and error-rate evidence. OTLP trace spans can also contribute latency when they contain a valid positive duration of no more than 24 hours. Spans without a valid duration, including synthetic spans derived from OTLP log records, remain recorded but do not become latency samples. Latency evaluation requires at least 10 samples in the baseline window, 5 in the recent window, and at least 50% duration coverage in both windows. The reported latency statistic is the mean of exact five-minute bucket p95 values. It is not a percentile recomputed across every request in the full multi-day window. Error-rate evaluation remains independent when latency is unavailable or below these gates. The expanded anomaly pipeline is live. API PR #84 activated recurring five-minute production execution on August 11, 2026. Three consecutive UTC boundaries at 20:20, 20:25, and 20:30 each had exactly one elected runner, completed in 655 ms, 350 ms, and 490 ms, and reported no errors. The initial run created 13 continuity incidents from existing gaps; the next two created no duplicates. ## Metrics (Preview) The metrics endpoint (`/api/v1/ingest/v1/metrics`) accepts OTLP metric exports and acknowledges them. Metrics-based anomaly detection is coming in Phase 2. # Quick Start Source: https://docs.meshai.dev/getting-started/quickstart Get monitoring in under 5 minutes ## Option A: OpenTelemetry (Zero Code if Already Instrumented) Already emitting OpenTelemetry traces from your agents? Point your existing OTLP exporter at MeshAI and you are done. No SDK, no proxy, no code changes. Go to [app.meshai.dev](https://app.meshai.dev) -> Connect -> Create telemetry key. The key needs only the `telemetry:write` scope. ```bash theme={null} export OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.meshai.dev/api/v1/ingest # Logs are served by api.meshai.dev, not the collector. Signal-specific # endpoints are used as-is, so this one carries the full path. export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://api.meshai.dev/api/v1/ingest/v1/logs export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer msh_YOUR_API_KEY" export OTEL_SERVICE_NAME=my-agent ``` MeshAI auto-discovers agents from the `service.name` resource attribute and extracts token usage from `gen_ai.*` conventions. Agents appear in the registry as telemetry arrives. See the [OpenTelemetry guide](/getting-started/opentelemetry) for details on what gets extracted. ## Option B: Proxy (Fastest, Zero Code) The MeshAI proxy sits between your agents and LLM providers. One env var change and you're monitoring. Go to [app.meshai.dev](https://app.meshai.dev) → Settings → Proxy Keys → Create. ```bash theme={null} # For Anthropic export ANTHROPIC_BASE_URL=https://proxy.meshai.dev/v1/anthropic/k/YOUR_PROXY_KEY # For OpenAI export OPENAI_BASE_URL=https://proxy.meshai.dev/v1/openai/k/YOUR_PROXY_KEY ``` No code changes needed. All requests automatically flow through MeshAI. ## Option C: Python SDK ```bash theme={null} pip install meshai-sdk ``` ```python theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...", agent_name="my-agent") client.register( framework="crewai", model_provider="openai", model_name="gpt-4o", ) ``` ```python theme={null} # Automatic heartbeats client.start_heartbeat() # Track usage (or use framework wrappers) client.track_usage( model_provider="openai", model_name="gpt-4o", input_tokens=1500, output_tokens=800, ) ``` ## What You'll See After connecting, your [dashboard](https://app.meshai.dev) shows: * **Agent Registry**: all your agents with status, framework, model * **Cost Attribution**: spend per agent, team, and model * **Anomaly Detection**: cost spikes, behavioral drift, security alerts * **Governance**: policy enforcement, audit trail, compliance score ## Next Steps OTLP endpoints, span conventions, and what gets extracted Detailed proxy configuration for all providers Auto-tracking for OpenAI, Anthropic, CrewAI, LangChain, AutoGen Set up your first governance policy Full API documentation # Attribute-Based Access Control (ABAC) Source: https://docs.meshai.dev/governance/abac Assign owners to agents with granular permissions - control who can invoke, configure, and delete each agent ABAC lets you assign owners (users, teams, or service accounts) to agents with fine-grained permissions. This establishes clear accountability for every agent in your organization and controls who can perform actions on each agent. ## Owner Types | Type | Description | Example | | ----------------- | -------------------- | ------------------- | | `user` | An individual user | `alice@company.com` | | `team` | A team or department | `ml-platform-team` | | `service_account` | A machine identity | `ci-cd-pipeline` | ## Permissions Each owner assignment includes a permissions object: | Permission | Description | Default | | --------------- | ------------------------------------------------------------ | ------- | | `can_invoke` | Can send requests through the proxy as this agent | `true` | | `can_configure` | Can update agent metadata, policies, and risk classification | `false` | | `can_delete` | Can delete the agent | `false` | ## Assign an Owner ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/owners \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "owner_type": "team", "owner_id": "ml-platform-team", "owner_name": "ML Platform Team", "permissions": { "can_invoke": true, "can_configure": true, "can_delete": false } }' ``` ```python SDK theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") client.assign_owner( agent_id="01ARZ3NDEKTSV4RRFFQ69G5FAV", owner_type="team", owner_id="ml-platform-team", owner_name="ML Platform Team", permissions={ "can_invoke": True, "can_configure": True, "can_delete": False, }, ) ``` ```json Response theme={null} { "success": true, "data": { "id": 1, "agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "owner_name": "ML Platform Team", "owner_type": "team" } } ``` The assign response is intentionally minimal - `id`, `agent_id`, `owner_name`, and `owner_type`. Fetch the full record (including `owner_id` and `permissions`) via the list endpoint below. ## List Agent Owners ```bash curl theme={null} curl https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/owners \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} owners = client.list_agent_owners("01ARZ3NDEKTSV4RRFFQ69G5FAV") ``` ```json Response theme={null} { "success": true, "data": [ { "id": 1, "owner_type": "team", "owner_id": "ml-platform-team", "owner_name": "ML Platform Team", "permissions": { "can_invoke": true, "can_configure": true, "can_delete": false } }, { "id": 2, "owner_type": "user", "owner_id": "alice@company.com", "owner_name": "Alice Chen", "permissions": { "can_invoke": true, "can_configure": false, "can_delete": false } } ] } ``` ## Remove an Owner ```bash curl theme={null} curl -X DELETE https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/owners/1 \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} client.remove_owner(agent_id="01ARZ3NDEKTSV4RRFFQ69G5FAV", owner_id=1) ``` ## List Agents by Owner Find all agents owned by a specific user, team, or service account: ```bash curl theme={null} curl https://api.meshai.dev/api/v1/owners/ml-platform-team/agents \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} agents = client.list_owner_agents("ml-platform-team") ``` ```json Response theme={null} { "success": true, "data": [ { "agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "permissions": { "can_invoke": true, "can_configure": true, "can_delete": false } }, { "agent_id": "01BX5ZZKBKACTAV9WEVGEMMVRZ", "permissions": { "can_invoke": true, "can_configure": true, "can_delete": true } } ] } ``` The response is a flat list of `{agent_id, permissions}` - it does not include the agent name; look it up separately via the agent registry if you need it for display. ## Audit Trail ABAC actions (assigning or removing an owner) do not currently emit their own audit event. If you need a record of ownership changes, track them through your own tooling around the API calls. ## Use Cases * **Non-human identity management** - Track the 144:1 ratio of NHIs to employees by assigning clear owners. * **Team accountability** - Every agent has at least one owner responsible for its behavior. * **Least-privilege access** - Grant `can_invoke` to runtime service accounts, `can_configure` to team leads only. * **Compliance** - EU AI Act Article 14 requires human oversight - ABAC documents who oversees each agent. * **Offboarding** - When a team member leaves, find all agents they own and reassign them. # Agent Lifecycle Management Source: https://docs.meshai.dev/governance/agent-lifecycle Set expiry dates, review schedules, and assign sponsors to enforce agent lifecycle governance Agent lifecycle management ensures that every AI agent has an expiry date, a review schedule, and a responsible sponsor. Expired and unreviewed agents surface automatically so you can decommission stale agents and enforce periodic access reviews. ## Lifecycle Fields | Field | Type | Description | | ------------------ | -------------------------------------------------- | --------------------------------------------- | | `expires_at` | ISO 8601 datetime | When the agent authorization expires | | `review_frequency` | `weekly` \| `monthly` \| `quarterly` \| `annually` | How often the agent must be reviewed | | `sponsor_id` | string | The person or team responsible for this agent | ## Set Agent Lifecycle ```bash curl theme={null} curl -X PATCH https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/lifecycle \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "expires_at": "2026-06-30T23:59:59Z", "review_frequency": "quarterly", "sponsor_id": "ml-platform-team" }' ``` ```python SDK theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") client.set_agent_lifecycle( agent_id="01ARZ3NDEKTSV4RRFFQ69G5FAV", expires_at="2026-06-30T23:59:59Z", review_frequency="quarterly", sponsor_id="ml-platform-team", ) ``` ```json Response theme={null} { "success": true, "data": { "agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "expires_at": "2026-06-30T23:59:59Z", "review_date": "2026-06-18T00:00:00Z", "review_frequency": "quarterly", "sponsor_id": "ml-platform-team" } } ``` You can set any combination of fields - all are optional. Only the fields you include are updated. ## List Expired Agents Returns agents whose `expires_at` date has passed. Use this to identify agents that need decommissioning or renewal. ```bash curl theme={null} curl https://api.meshai.dev/api/v1/agents/expired \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} expired = client.list_expired_agents() ``` ```json Response theme={null} { "success": true, "data": [ { "id": "01F8MECHZX3TBDSZ7XR8H8JHAF", "name": "legacy-support-bot", "expires_at": "2026-02-28T23:59:59Z" } ] } ``` This endpoint returns a plain list - it is not paginated and does not include `sponsor_id`, `status`, or `days_expired`. ## List Agents Due for Review Returns agents whose next review date has passed or is approaching. Use this to enforce periodic access reviews. ```bash curl theme={null} curl https://api.meshai.dev/api/v1/agents/due-review \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} due = client.list_agents_due_review() ``` ```json Response theme={null} { "success": true, "data": [ { "id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "name": "customer-support-agent", "review_date": "2026-03-15T00:00:00Z", "review_frequency": "quarterly" } ] } ``` This endpoint also returns a plain, unpaginated list, without `sponsor_id` or `days_overdue`. ## Review Frequency Options | Frequency | Review interval | | ----------- | --------------- | | `weekly` | Every 7 days | | `monthly` | Every 30 days | | `quarterly` | Every 90 days | | `annually` | Every 365 days | The `review_date` is automatically calculated as now plus the review interval whenever `review_frequency` is set or changed. ## Audit Trail Lifecycle changes (setting `expires_at`, `review_frequency`, or `sponsor_id`) do not currently emit their own audit event. ## Use Cases * **Compliance** - EU AI Act requires periodic review of high-risk AI systems. Set `review_frequency` to `quarterly` for high-risk agents. * **Shadow agent cleanup** - Set short expiry dates on newly discovered agents to force review. * **Team accountability** - Assign `sponsor_id` so every agent has a responsible owner. * **Decommissioning workflow** - Poll `GET /agents/expired` and call the [kill switch](/governance/kill-switch) yourself to block agents past their expiry; MeshAI does not auto-block expired agents today. # HITL Approvals Source: https://docs.meshai.dev/governance/approvals Human-in-the-loop approval workflow for AI agent requests When a `require_approval` policy matches, the MeshAI proxy blocks the request and queues it for human review. An authorized user must approve or deny each request before the agent can proceed. ## How It Works ``` Agent Request → MeshAI Proxy → Policy Engine ↓ require_approval matched? ↓ ↓ Yes No ↓ ↓ Return 403 Forward to LLM + queue item ↓ Dashboard Queue ↓ Approve / Deny ↓ Cache decision in Redis (TTL) ↓ Agent retries → Approved → Forward to LLM ``` The proxy evaluates policies and finds a `require_approval` match. The request is blocked with a `403` status and an approval item is created. The approval item appears in the MeshAI dashboard under **Governance → Approvals**. It includes the agent, the policy that triggered the block, and the request context. An authorized user reviews the item and submits a decision of `approved` or `denied`, identifying themselves as the reviewer. They can add a reason for the decision. Approved decisions are cached in Redis so the agent does not need re-approval on every request. The approval request itself carries an expiry (default TTL: 24 hours). The agent retries the request. The proxy checks the Redis cache, finds the approval, and forwards the request to the LLM provider. ## The 403 Response When a request requires approval, the agent receives: ```json theme={null} { "error": "approval_required", "approval_policy_id": 42 } ``` ## Approval Statuses | Status | Meaning | | ---------- | -------------------------------------------------- | | `pending` | Queued, waiting for a human decision | | `approved` | Approved - agent can retry | | `denied` | Denied - agent request will continue to be blocked | | `expired` | TTL elapsed without a decision | ## List Pending Approvals ```bash curl theme={null} curl https://api.meshai.dev/api/v1/approvals?status=pending \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") pending = client.list_approvals(status="pending") ``` ```json Response theme={null} { "success": true, "data": [ { "id": 17, "policy_id": 42, "agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "team_id": null, "request_context": { "provider": "openai", "model": "gpt-4o" }, "status": "pending", "expires_at": "2026-03-18T10:30:00Z", "resolved_at": null, "created_at": "2026-03-17T10:30:00Z" } ], "meta": { "total": 1, "page": 1, "limit": 50 } } ``` ## Approve or Deny ```bash curl (approve) theme={null} curl -X POST https://api.meshai.dev/api/v1/approvals/17/decide \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "reviewer_id": "user@company.com", "decision": "approved", "reason": "Verified agent configuration is correct" }' ``` ```bash curl (deny) theme={null} curl -X POST https://api.meshai.dev/api/v1/approvals/17/decide \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "reviewer_id": "user@company.com", "decision": "denied", "reason": "Agent not authorized for production use yet" }' ``` ```python SDK theme={null} # Approve client.decide_approval(17, reviewer_id="user@company.com", decision="approved", reason="Verified") # Deny client.decide_approval(17, reviewer_id="user@company.com", decision="denied", reason="Not authorized") ``` `reviewer_id` is required (1-100 characters) and `decision` must be `approved` or `denied`; `reason` is optional. ## Cache TTL When an approval is granted, the decision is cached in Redis so the agent does not need re-approval on every subsequent matching request. The approval request's expiry defaults to **24 hours** from creation - there is currently no per-policy field to override this default. # Article 50 Transparency Evidence Source: https://docs.meshai.dev/governance/article-50-transparency Record AI disclosure and content-marking evidence for EU AI Act Article 50 MeshAI can record whether an application reports that it disclosed an AI interaction or marked AI-generated content. The evidence is attached to OpenTelemetry spans, evaluated by governance policies, and retained with the span audit trail. These signals prove what MeshAI received in telemetry. They do not prove that a disclosure was visible to a person, that a content mark is valid, or that an application complies with Article 50. Treat missing attributes as missing evidence, not proof of non-compliance. ## Record disclosure evidence Add the following attributes to the span that represents the generated output: | Attribute | Type | Meaning | | ------------------------------------------------- | ------- | --------------------------------------------------------------------- | | `dev.meshai.gen_ai.output.ai_disclosure.provided` | boolean | The application reports that it provided an AI-interaction disclosure | | `dev.meshai.gen_ai.output.content_marking.type` | string | The application reports the content-marking mechanism, such as `c2pa` | The names use MeshAI's provisional reverse-domain namespace while the relevant OpenTelemetry semantic conventions are not standardized. ```python Python theme={null} span.set_attribute( "dev.meshai.gen_ai.output.ai_disclosure.provided", True, ) span.set_attribute( "dev.meshai.gen_ai.output.content_marking.type", "c2pa", ) ``` Send the attributes on the output span rather than on an unrelated parent span. MeshAI evaluates the evidence on the span where it appears. ## Enable evidence checks Create policies from these built-in templates: * `article-50-ai-disclosure-evidence` * `article-50-content-marking-evidence` The checks are observe-only. They record evaluation results for governance review but do not block proxy traffic. This avoids treating an absent telemetry attribute as proof that a user-facing control was absent. ## Record the served model For an auditable GPAI model inventory, emit the standard `gen_ai.response.model` attribute when the provider returns the model identifier it actually served. MeshAI stores that value separately from the requested model. ```python Python theme={null} span.set_attribute("gen_ai.request.model", "gpt-4.1") span.set_attribute("gen_ai.response.model", response.model) ``` Inventory rows have one of two attribution sources: * `response`: the emitter supplied `gen_ai.response.model`. * `request_fallback`: MeshAI only knows the requested or directly reported model. This does not confirm the exact version served by the provider. See the [Compliance API](/api-reference/compliance#gpai-model-inventory) to query or export the inventory. ## Generate an evidence pack Professional and higher plans can generate an Article 50 recorded-evidence pack from the dashboard or API. In the dashboard, open **Governance → Compliance**, choose a 24-hour, 7-day, or 30-day window, then click **Generate evidence pack**. The dashboard does not request the report until you click Generate. It presents recorded gaps first, followed by the disclosure and content-marking track summaries and a compact model inventory. Any retention clamp, request-fallback attribution, or truncation warning remains visible. Click **Download JSON** to create a dated JSON file in your browser from the generated report. The download does not make a separate export request. For automation, call `GET /api/v1/compliance/article-50/evidence-pack` with the `governance:read` scope. See the [Compliance API](/api-reference/compliance#article-50-evidence-pack) for date-range behavior and response semantics. The report's applicability is `not_determined` and its coverage is `unquantified`. A passing track means MeshAI recorded passing evaluations without recorded failures in the effective window. It does not prove that the obligation applies, that every output was observed, or that the user-facing control worked. The evidence pack reports an explicit status for each track: * `check_not_configured`: no enabled check or evaluation was recorded * `no_recorded_evidence`: no passing evidence was recorded * `gaps_recorded`: one or more evaluated interactions recorded a failure * `evidence_recorded`: passing evidence was recorded with no recorded failures An interaction can appear in both pass and fail counts if multiple policies disagree about the same span. Start with the `gaps` array and the track statements rather than treating counts as a compliance score. Requested dates are clamped to retained telemetry. The report preserves both requested and effective dates and sets `retention_clamped` when they differ. ## Evidence boundary Keep supporting application evidence alongside MeshAI's telemetry, including screenshots or UX tests for disclosures and verifier output for content credentials. MeshAI provides the received telemetry, policy evaluation, timestamps, and attribution needed to join those records into an audit package. Hash-chain heads and checkpoint receipts in the pack cover policy evaluations and audit events only. They do not provide integrity coverage for token usage records or the model inventory. # Audit Trail Source: https://docs.meshai.dev/governance/audit-trail Immutable audit log of every governance action - required by EU AI Act Article 12 MeshAI records an immutable audit event for every governance action. Audit events cannot be modified or deleted once created. This satisfies EU AI Act Article 12 (record-keeping) requirements. ## Event Types Event types actually emitted today: | Event Type | Description | | ---------------------- | -------------------------------------------------------- | | `agent.registered` | A new agent was registered | | `agent.updated` | Agent metadata was changed | | `agent.deleted` | An agent was removed | | `agent.blocked` | An agent was blocked via the kill switch | | `agent.unblocked` | A kill-switch block was removed | | `risk.classified` | Risk classification was assigned or changed for an agent | | `policy.created` | A new policy was created | | `policy.updated` | A policy was modified | | `policy.deleted` | A policy was removed | | `anomaly.acknowledged` | An anomaly was acknowledged | | `anomaly.resolved` | An anomaly was resolved | | `api_key.created` | A new API key was created | | `team.updated` | A team was updated | | `team.deleted` | A team was removed | Some governance actions do not (yet) emit their own audit event - for example quarantine/release-quarantine, ABAC owner assignment/removal, and agent lifecycle changes. Check the specific feature page for what it actually records. ## List Audit Events ```bash curl theme={null} curl "https://api.meshai.dev/api/v1/audit-trail?limit=50" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") events = client.list_audit_events(limit=50) ``` ```json Response theme={null} { "success": true, "data": [ { "id": 1042, "event_type": "agent.registered", "actor_type": "api_key", "actor_id": "key_abc123", "resource_type": "agent", "resource_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "description": "Agent registered: production-summarizer", "details": { "framework": "crewai" }, "proxy_request_id": null, "created_at": "2026-03-17T10:00:00Z" }, { "id": 1041, "event_type": "anomaly.acknowledged", "actor_type": "user", "actor_id": "admin@company.com", "resource_type": "anomaly", "resource_id": "789", "description": "Anomaly acknowledged", "details": { "anomaly_type": "cost_spike" }, "proxy_request_id": null, "created_at": "2026-03-17T09:45:00Z" } ], "meta": { "total": 234, "page": 1, "limit": 50 } } ``` ## Filtering Filter audit events by type, actor, resource, and time range using `start`/`end`: ```bash curl theme={null} # By event type curl "https://api.meshai.dev/api/v1/audit-trail?event_type=agent.blocked" \ -H "Authorization: Bearer msh_YOUR_API_KEY" # By resource (e.g. an agent) curl "https://api.meshai.dev/api/v1/audit-trail?resource_id=01ARZ3NDEKTSV4RRFFQ69G5FAV" \ -H "Authorization: Bearer msh_YOUR_API_KEY" # By date range curl "https://api.meshai.dev/api/v1/audit-trail?start=2026-03-01T00:00:00Z&end=2026-03-17T23:59:59Z" \ -H "Authorization: Bearer msh_YOUR_API_KEY" # Combined filters curl "https://api.meshai.dev/api/v1/audit-trail?event_type=anomaly.acknowledged&start=2026-03-01T00:00:00Z&limit=100" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} # By event type events = client.list_audit_events(event_type="agent.blocked") # By resource events = client.list_audit_events(resource_id="01ARZ3NDEKTSV4RRFFQ69G5FAV") # By date range events = client.list_audit_events( start="2026-03-01T00:00:00Z", end="2026-03-17T23:59:59Z", ) ``` Date ranges cannot exceed 180 days per request; free-tier tenants additionally have their window clamped to their retention period (see below). ## Export Export audit events in CSV or JSON format for compliance reporting and external audit tools, using `fmt`: ```bash curl (CSV) theme={null} curl "https://api.meshai.dev/api/v1/audit-trail/export?fmt=csv&start=2026-01-01T00:00:00Z" \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -o audit-trail.csv ``` ```bash curl (JSON) theme={null} curl "https://api.meshai.dev/api/v1/audit-trail/export?fmt=json&start=2026-01-01T00:00:00Z" \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -o audit-trail.json ``` ```python SDK theme={null} # Export as CSV csv_data = client.export_audit_events(fmt="csv", start="2026-01-01T00:00:00Z") # Export as JSON json_data = client.export_audit_events(fmt="json", start="2026-01-01T00:00:00Z") ``` Export requires the Professional plan or above. Free and Starter tenants receive a `402` with an upgrade path. ## Retention | Plan | Retention | | --------------- | --------- | | Free | 7 days | | Starter | 90 days | | Professional | 395 days | | Enterprise | Unlimited | | Enterprise Plus | Unlimited | # Decision Evidence Source: https://docs.meshai.dev/governance/decision-evidence The per-decision record MeshAI keeps when a policy evaluates an agent action Every agent action that MeshAI governs produces a decision: a policy was consulted, an agent was evaluated, and an outcome was reached. MeshAI records that decision as a first-class evidence record, separate from the request telemetry it relates to. Decision evidence is what an auditor reads when the question is not "what did the agent do" but "was it allowed, and on what basis." Evidence records are produced on two paths: the proxy evaluates policies in the request path for traffic it fronts, and the OTLP ingest evaluates policies observe-only for activity reported from anywhere else. ## What a decision record carries These are the fields returned by the API for each evaluation: | Field | Type | Meaning | | --------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | integer | Evidence record identifier | | `policy_id` | integer | The policy consulted for this decision | | `agent_id` | string | The agent that was evaluated. Identity is resolved before evaluation, whether the agent is bound to the calling credential or self-asserted and discovered | | `result` | string | `pass` or `fail` | | `reason` | string | Human-readable basis for the outcome, for example which rule matched | | `context` | object | Producer detail: which path produced the record, the enforcement action taken, and matched categories where applicable | | `proxy_request_id` | integer | Linkage to the proxied request, where applicable | | `trace_id`, `span_id` | string | Linkage to the surrounding trace, for records built from ingested OpenTelemetry activity | | `evaluated_at` | timestamp | When the decision was made | Request-level attribution is recorded alongside on the request record itself: the API key identity, agent, team, provider, requested model, token usage, cost, and upstream status and latency. ## Decision outcomes Outcomes in production are richer than allow and deny. A request can be denied by policy, held for [human approval](/governance/approvals), rate limited, stopped at a budget limit, blocked by the [prompt-injection scan](/governance/prompt-injection), refused by model routing rules, or have its response content acted on by a [PII policy](/governance/pii-filter) (block, redact, or observe). An agent under the [kill switch](/governance/kill-switch) is refused outright. Each of these is a different answer to a different question, and the evidence record keeps them distinguishable rather than flattening them into a single allow/deny bit. ## Query decision evidence ```bash curl theme={null} curl "https://api.meshai.dev/api/v1/governance/policy-evaluations?result=fail&limit=50" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` Filter by `policy_id`, `agent_id`, or `result` (`pass`, `fail`). Results are also visible in the dashboard's Eval Log. Durable evidence rows are written today for content-policy evaluations on proxied responses and for all activity evaluated from OpenTelemetry ingest. Gateway enforcement denials return their decision and basis in the response; unifying those onto the same durable record is in progress. Check this page as coverage expands. ## Standards alignment The record above maps directly onto the direction of the OpenTelemetry GenAI semantic conventions for governance operations: a decision emitted by the deciding component, carrying the principal, the policy consulted, and the outcome, correlated onto the trace of the activity it governed. MeshAI participates in that standardization work and tracks it closely. # EU AI Act Coverage Source: https://docs.meshai.dev/governance/eu-ai-act Article-by-article mapping of EU AI Act requirements to MeshAI features The EU AI Act (Regulation 2024/1689) is phasing in on a staggered timeline. Prohibited practices have applied since **February 2025**, GPAI obligations since **August 2025**, and general enforcement of the Act, including transparency obligations, began on **2 August 2026**. Under the Digital Omnibus, the grace period for AI-generated-content marking runs until **2 December 2026**, Annex III high-risk obligations apply from **2 December 2027**, and Annex I high-risk obligations from **August 2028**. MeshAI maps its features to specific articles so you can demonstrate compliance ahead of those dates. High-risk dates reflect the Digital Omnibus amendments adopted in June 2026. ## Coverage Summary | Article | Topic | MeshAI Feature | Coverage | | ------- | ------------------------------------ | ------------------------------------------------------------ | ---------------- | | Art. 6 | Classification of high-risk AI | [Risk Classification](/governance/risk-classification) | Full | | Art. 12 | Record-keeping | [Audit Trail](/governance/audit-trail) | Full | | Art. 13 | Transparency | Transparency Cards | Full | | Art. 14 | Human oversight | [HITL Approvals](/governance/approvals) | Full | | Art. 26 | Deployer obligations | Agent Registry + Governance | Full | | Art. 27 | Fundamental rights impact assessment | [FRIA](/governance/fria) | Full | | Art. 50 | Transparency for certain AI systems | [Transparency Evidence](/governance/article-50-transparency) | Evidence support | | Art. 73 | Serious incident reporting | [Incident Reporting](/governance/incidents) | Full | ## Article 6 - Classification of High-Risk AI Systems **Requirement**: Organizations must classify AI systems based on their risk level per Annex III categories. **MeshAI coverage**: The [Risk Classification](/governance/risk-classification) feature lets you assign risk levels (minimal, limited, high, unacceptable) to each agent. AI-assisted suggestions analyze agent metadata against Annex III categories. ## Article 12 - Record-Keeping **Requirement**: High-risk AI systems must have automatic logging capabilities that record events throughout the system's lifecycle. **MeshAI coverage**: The [Audit Trail](/governance/audit-trail) captures core governance actions as immutable events - agent registration/updates/deletion, kill-switch blocks, risk classification, policy changes, and anomaly acknowledgement/resolution. Events are timestamped, attributed to an actor, and exportable in CSV/JSON. (Some actions - approvals, incidents, FRIA, quarantine, ABAC, lifecycle - do not yet emit their own audit event; see each feature's page.) ## Article 13 - Transparency and Information to Deployers **Requirement**: High-risk AI systems must be designed to be sufficiently transparent to enable deployers to interpret outputs and use them appropriately. **MeshAI coverage**: Transparency Cards are auto-generated for each agent, documenting purpose, capabilities, limitations, model provider, and risk classification. Access via `GET /agents/{id}/transparency-card`. ## Article 14 - Human Oversight **Requirement**: High-risk AI systems must be designed to allow effective human oversight during use. **MeshAI coverage**: [HITL Approvals](/governance/approvals) - via the `require_approval` policy type - inline-enforce human review before agents can execute certain actions. `require_human_review` is a periodic-review flag: it is recorded as evidence, not enforced inline, so it documents a review cadence rather than blocking an action in real time. ## Article 26 - Obligations of Deployers **Requirement**: Deployers must implement appropriate technical and organizational measures, monitor AI system operation, and keep logs. **MeshAI coverage**: The Agent Registry provides a complete inventory of all deployed AI agents. Governance policies enforce organizational rules. Real-time monitoring detects anomalies. All actions are logged in the audit trail. ## Article 27 - Fundamental Rights Impact Assessment **Requirement**: Deployers of high-risk AI must conduct a fundamental rights impact assessment (FRIA) before deployment. **MeshAI coverage**: The [FRIA feature](/governance/fria) provides structured templates covering all six required assessment areas (a–f). Each FRIA is immutable once created - reassessing an agent creates a new, incrementing version rather than editing the prior one. ## Article 50 - Transparency Obligations for Certain AI Systems **Requirement**: Providers of AI systems that interact with natural persons must ensure users are informed they are interacting with AI. **MeshAI coverage**: [Article 50 Transparency Evidence](/governance/article-50-transparency) records application-reported AI disclosure and content-marking signals from OpenTelemetry spans. Built-in, observe-only policies evaluate whether the signals are present without treating missing telemetry as proof of non-compliance. Transparency Cards document agent purpose and interaction patterns, and the `limited` risk classification flags agents that may require transparency disclosures. ## Article 73 - Reporting of Serious Incidents **Requirement**: Providers and deployers must report serious incidents to the relevant market surveillance authority within strict deadlines. **MeshAI coverage**: The [Incident Reporting](/governance/incidents) feature provides structured incident creation, automatic deadline tracking (15-day and 2-day timelines), and authority notification support. ## Readiness Score MeshAI calculates a [readiness score](/governance/readiness-score) (0–120) across 7 components that map to these articles. Use it to track your compliance progress and identify gaps ahead of the Annex III (2 December 2027) and Annex I (August 2028) deadlines. # Fundamental Rights Impact Assessment Source: https://docs.meshai.dev/governance/fria Article 27 FRIA - structured assessment of AI impact on fundamental rights EU AI Act Article 27 requires deployers of high-risk AI systems to conduct a **Fundamental Rights Impact Assessment (FRIA)** before putting the system into use. MeshAI provides structured FRIA creation, storage, and versioning. ## When Is a FRIA Required? A FRIA is required when: * The agent is classified as **high** or **unacceptable** risk * The agent is used by a public body or private entity providing public services * The agent performs profiling of natural persons ## Required Fields Article 27(1) specifies six assessment areas (a–f). MeshAI enforces all six, plus who assessed the agent: | Field | Article 27(1) Reference | Description | | -------------------------- | ----------------------- | --------------------------------------------------------------------------- | | `intended_purpose` | Art. 27(1)(a) | The system's intended purpose | | `processes_description` | Art. 27(1)(a) | Description of the deployer's processes in which the AI system will be used | | `usage_period` | Art. 27(1)(b) | Period of intended use | | `usage_frequency` | Art. 27(1)(b) | How often and how extensively the system will be used | | `affected_categories` | Art. 27(1)(c) | List of categories of natural persons and groups likely to be affected | | `specific_risks` | Art. 27(1)(d) | List of specific risks of harm likely to impact the identified categories | | `human_oversight_measures` | Art. 27(1)(e) | Description of human oversight measures implemented | | `risk_mitigation_measures` | Art. 27(1)(f) | Actions to be taken if risks materialize | | `complaint_mechanisms` | Art. 27(1)(f) | How affected persons can file complaints | | `internal_governance` | Art. 27(1)(f) | Internal governance arrangements for risk materialization | | `assessed_by` | Metadata | Who performed the assessment | ## Create a FRIA ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/fria \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "intended_purpose": "Rank job applicants for open HR positions", "processes_description": "The AI agent reviews job applications and ranks candidates for the HR team. It processes CVs, cover letters, and assessment results.", "usage_period": "Ongoing, reviewed quarterly", "usage_frequency": "Daily, by 5 HR managers, ~500 applications/month", "affected_categories": ["Job applicants"], "specific_risks": ["Discriminatory bias in candidate ranking based on gender, age, ethnicity, or disability"], "human_oversight_measures": "All AI-ranked lists are reviewed by a human HR manager before any hiring decision. The agent cannot reject candidates - it only suggests rankings.", "risk_mitigation_measures": "If bias is detected: immediately suspend the agent, notify affected applicants, and conduct manual review of all affected applications.", "complaint_mechanisms": "Applicants may email hr-appeals@company.com to request manual review of their ranking.", "internal_governance": "The DPO reviews quarterly bias audits and signs off on continued use.", "assessed_by": "user@company.com" }' ``` ```python SDK theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") fria = client.create_fria( agent_id="01ARZ3NDEKTSV4RRFFQ69G5FAV", intended_purpose="Rank job applicants for open HR positions", processes_description="The AI agent reviews job applications and ranks candidates...", usage_period="Ongoing, reviewed quarterly", usage_frequency="Daily, by 5 HR managers, ~500 applications/month", affected_categories=["Job applicants"], specific_risks=["Discriminatory bias in candidate ranking"], human_oversight_measures="All AI-ranked lists reviewed by a human HR manager...", risk_mitigation_measures="If bias is detected: suspend agent, notify affected applicants...", complaint_mechanisms="Applicants may email hr-appeals@company.com...", internal_governance="The DPO reviews quarterly bias audits...", assessed_by="user@company.com", ) ``` ```json Response theme={null} { "success": true, "data": { "id": 7, "agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "version": 1, "intended_purpose": "Rank job applicants for open HR positions", "processes_description": "The AI agent reviews job applications and ranks candidates...", "usage_period": "Ongoing, reviewed quarterly", "usage_frequency": "Daily, by 5 HR managers, ~500 applications/month", "affected_categories": ["Job applicants"], "specific_risks": ["Discriminatory bias in candidate ranking"], "human_oversight_measures": "All AI-ranked lists reviewed by a human HR manager...", "risk_mitigation_measures": "If bias is detected: suspend agent, notify affected applicants...", "complaint_mechanisms": "Applicants may email hr-appeals@company.com...", "internal_governance": "The DPO reviews quarterly bias audits...", "assessed_by": "user@company.com (key:a1b2c3d4)", "status": "draft", "submitted_at": null, "created_at": "2026-03-17T10:00:00Z" } } ``` `assessed_by` is bound to the authenticated API key (a `(key:...)` suffix is appended) to prevent identity spoofing. ## Submit a FRIA After review, submit the FRIA to mark it as finalized: ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/fria/7/submit \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} client.submit_fria(fria_id=7) ``` Submitting a FRIA changes its status from `draft` to `submitted` and sets `submitted_at`. Submitting an already-submitted FRIA returns a conflict error. ## Get / List FRIAs ```bash curl theme={null} # Latest FRIA for an agent curl https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/fria \ -H "Authorization: Bearer msh_YOUR_API_KEY" # List, optionally filtered by agent_id / status curl "https://api.meshai.dev/api/v1/fria?agent_id=01ARZ3NDEKTSV4RRFFQ69G5FAV&status=submitted" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} fria = client.get_fria("01ARZ3NDEKTSV4RRFFQ69G5FAV") frias = client.list_frias(agent_id="01ARZ3NDEKTSV4RRFFQ69G5FAV", status="submitted") ``` ## Versioning FRIAs are immutable once created - there is no update endpoint. To reassess an agent, create a new FRIA for the same agent; it is stored as the next incrementing `version`, and prior versions are preserved and retrievable via `GET /fria`. ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/fria \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "intended_purpose": "...", "processes_description": "...", "usage_period": "...", "usage_frequency": "...", "affected_categories": ["..."], "specific_risks": ["Updated risk assessment after bias audit"], "human_oversight_measures": "...", "risk_mitigation_measures": "...", "complaint_mechanisms": "...", "internal_governance": "...", "assessed_by": "user@company.com" }' ``` This creates version 2 for the agent; version 1 remains available via `GET /fria?agent_id=...`. # Incident Reporting Source: https://docs.meshai.dev/governance/incidents EU AI Act Article 73 serious incident reporting with deadline tracking EU AI Act Article 73 requires providers and deployers to report serious incidents involving high-risk AI systems to the relevant market surveillance authority. MeshAI provides structured incident creation, deadline tracking, and authority notification support. ## What Is a Serious Incident? Article 3(49) defines a serious incident as an event that directly or indirectly leads to or could have led to: * Death or serious damage to health * Serious and irreversible disruption of critical infrastructure management * Breach of fundamental rights obligations ## Severity Incidents are recorded with one of four severity levels: | Severity | Use for | | ---------- | --------------------------------------------------------- | | `low` | Minor issue, limited impact | | `medium` | Moderate impact, contained | | `high` | Significant impact requiring prompt attention | | `critical` | Severe impact - potential Article 73 reporting obligation | ## Reporting Deadlines | Deadline | Condition | Timeframe | | ----------- | ------------------------------------ | -------------------------- | | **2 days** | `is_widespread` is `true` | Within 2 days of creation | | **15 days** | `is_widespread` is `false` (default) | Within 15 days of creation | MeshAI automatically calculates `notification_deadline` when the incident is created, based on `is_widespread`. ## Create an Incident ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/incidents \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "title": "Discriminatory output in hiring agent", "description": "The HR screening agent systematically ranked female candidates lower than male candidates with equivalent qualifications over a 2-week period.", "severity": "high", "affected_persons": "Approximately 120 job applicants", "reported_by": "user@company.com", "is_widespread": false }' ``` ```python SDK theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") incident = client.create_incident( agent_id="01ARZ3NDEKTSV4RRFFQ69G5FAV", title="Discriminatory output in hiring agent", description="The HR screening agent systematically ranked female candidates lower...", severity="high", affected_persons="Approximately 120 job applicants", reported_by="user@company.com", is_widespread=False, ) ``` `reported_by` is required and is bound to the authenticated API key. `anomaly_event_id` is an optional integer linking the incident to an ML-detected anomaly. `root_cause` and `corrective_actions` are not create-time fields - they're set later via the update endpoint below. ```json Response theme={null} { "success": true, "data": { "id": 12, "agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "title": "Discriminatory output in hiring agent", "description": "The HR screening agent systematically ranked female candidates lower...", "severity": "high", "status": "reported", "affected_persons": "Approximately 120 job applicants", "root_cause": null, "corrective_actions": null, "anomaly_event_id": null, "authority_notified": false, "authority_notified_at": null, "notification_deadline": "2026-04-01T10:00:00Z", "reported_by": "user@company.com (key:a1b2c3d4)", "reported_at": "2026-03-17T10:00:00Z", "resolved_at": null } } ``` ## Incident Statuses | Status | Description | | --------------- | ---------------------------------------------------- | | `reported` | Incident created, not yet under active investigation | | `investigating` | Root cause analysis in progress | | `resolved` | Investigation complete, incident resolved | | `notified` | Authority has been notified | ## Track an Incident ```bash curl theme={null} curl https://api.meshai.dev/api/v1/incidents/12 \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} incident = client.get_incident(12) ``` ## Update an Incident Use the update endpoint to record investigation progress, root cause, corrective actions, and authority notification: ```bash curl theme={null} curl -X PATCH https://api.meshai.dev/api/v1/incidents/12 \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "status": "resolved", "root_cause": "Training data contained historical hiring bias that was not sufficiently mitigated.", "corrective_actions": "All 120 affected applications have been manually re-reviewed. 8 candidates were re-ranked and contacted." }' ``` ```python SDK theme={null} client.update_incident( 12, status="resolved", root_cause="Training data contained historical hiring bias.", corrective_actions="All 120 affected applications manually re-reviewed.", ) ``` Setting `status: "resolved"` records `resolved_at` automatically. ## Notify the Authority There is no dedicated "notify authority" endpoint. Recording that you've notified the relevant market surveillance authority is the same update endpoint, setting `authority_notified: true`: ```bash curl theme={null} curl -X PATCH https://api.meshai.dev/api/v1/incidents/12 \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "status": "notified", "authority_notified": true }' ``` ```python SDK theme={null} client.update_incident(12, status="notified", authority_notified=True) ``` Setting `authority_notified: true` records `authority_notified_at` automatically. `IncidentUpdate` accepts `status`, `root_cause`, `corrective_actions`, and `authority_notified` - track the authority name, contact details, and any filing notes in your own systems, since MeshAI does not have dedicated fields for them. ## Export an Evidence Pack One call assembles the incident report plus the telemetry evidence recorded around it into a single document shaped for an Article 73 filing: ```bash theme={null} curl "https://api.meshai.dev/api/v1/incidents/12/evidence-pack?window_hours=24" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` The pack contains: | Section | Contents | | ----------------------------- | --------------------------------------------------------------------------------------------- | | `incident` | The full incident report | | `agent` | Identity snapshot including risk classification; preserved even if the agent is later deleted | | `evidence.policy_evaluations` | Policy checks in the window, with policy names and fail count | | `evidence.approvals` | Approval requests with the human decisions inlined (who decided, when, why) | | `evidence.anomalies` | Anomaly events in the window, including acknowledgement timestamps | | `evidence.usage` | Token and cost totals plus a by-model breakdown | | `evidence.audit_events` | Agent-scoped audit trail, plus operator actions on the incident's anomalies | | `linked_anomaly` | The ML detection that triggered the incident, if linked | | `article_73` | Deadline status: days remaining, overdue flag, and whether notification was late | Window semantics that matter for evidence: * The telemetry window (`window_hours`, default 24, max 168) is anchored at the incident's `reported_at` and looks backward: the lead-up to the incident. * The audit trail additionally runs through generation time, because the human response to an incident happens after it is reported. Acknowledgements, kill switches, and reclassifications are part of the record. * `deadline_days_remaining` uses a ceiling, so 47 hours remaining reads as 2 days and a 1-hour lapse reads as 0 days with `overdue: true`. * Record lists are capped at 200 entries per category with uncapped totals, so truncation is always detectable (`total` exceeds the record count). Evidence pack export requires the Professional plan or above, matching the audit trail export entitlement. Starter and free tenants receive a 402 with an upgrade path. ## Dashboard Alerts The MeshAI dashboard shows: * **Active incidents** with countdown timers to reporting deadlines * **Overdue incidents** highlighted in red * **Deadline approaching** warnings 48 hours before the deadline # Agent Kill Switch Source: https://docs.meshai.dev/governance/kill-switch Instantly block any agent from making LLM requests - enforced in real-time at the proxy layer The kill switch lets you immediately block an agent from making any LLM requests through the MeshAI proxy. Blocks are cached in Redis for instant enforcement - the proxy returns `403 Forbidden` for any request from a blocked agent. ## How It Works 1. You call `POST /agents/{id}/block` with a reason. 2. The API writes the block to the database and publishes it to Redis. 3. The proxy checks Redis on every incoming request - blocked agents get an immediate `403`. 4. An `agent.blocked` audit event is emitted automatically. 5. To restore access, call `POST /agents/{id}/unblock` - an `agent.unblocked` event is emitted. ## Block an Agent ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/block \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "reason": "Anomalous behavior detected - cost spike 10x above baseline" }' ``` ```python SDK theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") client.block_agent( agent_id="01ARZ3NDEKTSV4RRFFQ69G5FAV", reason="Anomalous behavior detected - cost spike 10x above baseline", ) ``` ```json Response theme={null} { "success": true, "data": { "agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "blocked": true, "reason": "Anomalous behavior detected - cost spike 10x above baseline" } } ``` ## Unblock an Agent ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/unblock \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} client.unblock_agent(agent_id="01ARZ3NDEKTSV4RRFFQ69G5FAV") ``` ```json Response theme={null} { "success": true, "data": { "agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "blocked": false } } ``` ## What the Agent Sees When a blocked agent sends a request through the proxy, it receives: ```json theme={null} { "error": "Agent is blocked: Anomalous behavior detected - cost spike 10x above baseline" } ``` This is compatible with all LLM SDK error handling - OpenAI, Anthropic, and other clients will raise their standard authentication/permission errors. ## Audit Trail Every block and unblock action emits an audit event: | Event Type | Description | | ----------------- | --------------------------------------------- | | `agent.blocked` | Agent was blocked (includes reason and actor) | | `agent.unblocked` | Agent block was removed (includes actor) | Query block-related audit events: ```bash theme={null} curl "https://api.meshai.dev/api/v1/audit-trail?event_type=agent.blocked" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ## Enforcement Architecture The kill switch uses Redis for sub-millisecond enforcement: * **Write path**: API writes block to PostgreSQL and publishes to Redis. * **Read path**: Proxy checks Redis on every request (before policy evaluation). * **Fail-open**: If Redis is unavailable, the proxy falls back to allowing the request (same as policy cache behavior). * **Latency**: Block takes effect within milliseconds of the API call. ## Use Cases * **Incident response** - Immediately stop a compromised or malfunctioning agent. * **Cost containment** - Block an agent that is burning through budget unexpectedly. * **Compliance** - Emergency shutdown to satisfy regulatory requirements (EU AI Act Article 14). * **Anomaly response** - Automated block triggered by anomaly detection (coming soon). # Oversight Metrics Source: https://docs.meshai.dev/governance/oversight-metrics Human oversight as measurable numbers: intervention demand, override rate, unattended approvals, and approval latency per agent EU AI Act Article 14 requires human oversight that is effective, not decorative. Oversight metrics turn that requirement into numbers computed continuously from your existing governance data: how often humans intervene, how fast they respond, how often they override the agent, and how many approval requests expire with nobody watching. No additional instrumentation is required. The metrics are derived from policy evaluations and approval workflow records you already generate. ## The Metrics | Metric | Definition | What it tells you | | ------------------------------ | -------------------------------------------------------------------------------- | -------------------------------------------------- | | `evaluations.fail_rate` | Failed policy evaluations over decided (pass + fail) | How often agent activity violates policy | | `approvals.requested` | Approval requests created in the window | Human intervention demand | | `override_rate` | Denied over human-resolved (approved + denied) | When humans reviewed, how often they said no | | `unattended_rate` | Expired over requested | Approvals that lapsed with no human decision | | `avg_approval_latency_seconds` | Mean time from request to human decision | Oversight responsiveness | | `defer_to_human_policies` | Enabled require-approval / require-human-review policies that apply to the agent | Whether defer-to-human criteria are defined at all | | `review_overdue` | Whether the agent's scheduled review date has passed | Review currency | The unattended rate is the most honest single measure of whether human oversight exists outside the policy document: the approval mechanism existed, and nobody decided in time. A stale-pending request counts as expired the moment its expiry passes, even before the background sweeper updates its status. ## Per-Agent Scorecard ```bash theme={null} curl "https://api.meshai.dev/api/v1/agents/agt_abc123/oversight?start=2026-06-01T00:00:00Z" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```json Response theme={null} { "success": true, "data": { "agent_id": "agt_abc123", "period_start": "2026-06-01T00:00:00Z", "period_end": "2026-07-01T00:00:00Z", "risk_level": "high", "review_overdue": false, "defer_to_human_policies": 2, "evaluations": { "total": 1240, "passed": 1180, "failed": 60, "fail_rate": 0.0484 }, "approvals": { "requested": 18, "approved": 12, "denied": 3, "expired": 2, "pending": 1 }, "override_rate": 0.2, "unattended_rate": 0.1111, "avg_approval_latency_seconds": 340.5 } } ``` ## Tenant-Wide Summary ```bash theme={null} curl https://api.meshai.dev/api/v1/oversight/summary \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` Returns the same metrics aggregated across all agents, plus `agents_evaluated` (distinct agents with policy evaluations in the window). ## Window Semantics * Both endpoints accept `start` and `end` query parameters (ISO 8601). Default window is the last 30 days; the maximum range is 180 days. * Timestamps without a timezone offset are treated as UTC. * **Historical windows are reproducible.** Approval expiry is judged as of the window end, not the current time, so a report for a closed period returns the same numbers every time you run it. A request that lapsed after your window closed was still pending within it. * Requires the `governance:read` scope. ## How Defer-to-Human Counting Works `defer_to_human_policies` counts enabled policies of type `require_approval` or `require_human_review` whose conditions match the agent, using the same condition matcher the policy engine uses at evaluation time, including [risk-tiered scoping](/governance/risk-classification). An unclassified agent never matches a policy scoped to specific risk levels, so classifying your agents is a prerequisite for risk-tiered oversight coverage. ## Related * [Approvals](/governance/approvals): the human-in-the-loop workflow these metrics measure * [Risk Classification](/governance/risk-classification): risk levels that scope defer-to-human policies * [Incident Reporting](/governance/incidents): the evidence pack cites oversight activity in the incident window # Governance Overview Source: https://docs.meshai.dev/governance/overview Unified governance for AI agents - policies, approvals, audit trail, risk classification, and compliance MeshAI's governance engine lets you define, enforce, and audit rules across every AI agent in your organization. It covers five areas: Eight policy types, with enforcement that varies by type - some block inline at the proxy, others are recorded as evidence. Block models, cap budgets, require approval, and more. Human-in-the-loop workflow. The proxy blocks requests that require approval and queues them for your team to review. EU AI Act risk levels (minimal, limited, high, unacceptable) assigned to each agent. AI-assisted suggestions available. Immutable log of every governance action. Filter, search, and export for compliance audits. ## How It Works Governance enforcement happens at two layers: 1. **Proxy layer** - `model_allowlist`, `block_provider`, and `require_approval` policies are evaluated inline on every LLM request and can block it with a `403`. `budget_limit` and `rate_limit` are enforced separately at the proxy-key/team level (`429`). Prompt injection scanning is always-on, independent of policies. See [Enforcement model](/governance/policies#enforcement-model) for the full picture, including policy types that are evidence-only today. 2. **API layer** - registration, classification, and administrative actions go through the API directly; they are not policy-gated by the proxy. ``` Agent Request → MeshAI Proxy → Policy Engine → Allow / Block (403) ↓ Audit Event logged ``` ## Quick Start Use the [SDK](/sdk-reference/agents) or [API](/api-reference/agents) to register agents with framework, model, and environment metadata. Assign an [EU AI Act risk level](/governance/risk-classification) to each agent. Use the AI-assisted suggestion endpoint for guidance. Define [policies](/governance/policies) - model allowlists, budget limits, approval requirements - scoped globally or per-agent. Every action is recorded in the [audit trail](/governance/audit-trail). Export events for compliance reporting. Use the [readiness score](/governance/readiness-score) to measure your organization's EU AI Act compliance posture. ## EU AI Act Compliance MeshAI maps directly to EU AI Act requirements. See the dedicated pages: Article-by-article mapping of what MeshAI covers. Fundamental Rights Impact Assessments (Article 27). Serious incident reporting per Article 73. 7-component compliance score (0–120). # Sanitized Input Capture Source: https://docs.meshai.dev/governance/payload-capture Opt in to bounded, redacted input evidence from OTLP spans and proxy requests Payload capture is an opt-in evidence feature. It is disabled when a tenant has no configuration and remains disabled until a key with `payload:write` enables it. | Control | Default | | ----------------- | --------------------------------------------------- | | Capture | **Off** | | Activation | Explicit tenant opt-in | | Content direction | Allowlisted inputs only; outputs are never captured | | Retention | Tenant-selected 1 to 30 days, capped by plan | | Redaction | Mandatory patterns, then tenant rules | | Failure behavior | Best effort; telemetry and proxy requests continue | Enabling capture is your organization's processing instruction. It does not establish end-user consent or another lawful basis. Document the purpose and lawful basis before enabling it. ## Supported input paths ### OpenTelemetry For a span classified as generative AI, capture can read these emitted attributes: * `gen_ai.input.messages`, as a JSON object or array encoded as a string * `gen_ai.system_instructions`, as a JSON object or array encoded as a string * `gen_ai.retrieval.query.text`, as a string Your application or instrumentation must emit these attributes. Enabling capture does not cause an OpenTelemetry emitter to collect content, and many instrumentations omit content by default. Malformed values are dropped. Output messages and retrieved documents are not captured. ### MeshAI proxy The proxy supports input normalization for OpenAI, Anthropic, NVIDIA, Google Vertex, and AWS Bedrock requests. It selects textual system, message, prompt, and input fields from supported inference requests. Unknown fields, response or output fields, authorization data, headers, binary content, and image URLs are excluded. Capture occurs only for requests that pass governance and prompt-injection checks and are about to be forwarded. A request blocked before provider forwarding is not captured. Streaming and non-streaming requests use the same input capture path. Provider responses and completions are never captured. ## Redaction and bounds Mandatory redaction runs before tenant rules and covers common emails, Social Security numbers, payment card numbers, phone numbers, IP addresses, and known secret patterns. Tenant rules then redact matching configured fields and patterns. Mandatory redaction cannot be disabled, and tenant rules cannot restore a value removed by a mandatory rule. The result is pattern-sanitized evidence, not anonymous or PII-free data. Names, addresses, unrecognized identifiers, and novel secret formats can remain. Minimize content at the emitter and application boundary rather than relying only on pattern matching. Redaction uses bounded regular-expression execution. A timeout or redaction error discards the capture rather than storing unredacted content. Oversized raw inputs are also discarded, and sanitized payloads that exceed the storage bound are stored only in a truncated envelope. Raw content is not queued or deliberately written to application logs, policy-evaluation rows, audit details, or error descriptions by the capture pipeline. ## Retention and disabling Configure a retention period from 1 through 30 days, limited further by your plan's telemetry retention. Payload content is not eligible for unlimited retention. The `expires_at` value is fixed when each sanitized record is created, so changing retention affects new records only. Expired records are removed by a scheduler and can remain after the recorded expiry until that scheduler runs. Disabling capture stops requests that observe the disabled configuration from starting capture. Work already in flight or queued can still finish. Disabling does not delete existing sanitized records; they remain until scheduled expiry deletion or a separately administered tenant purge. ## Missing evidence and failures Capture is best effort and never causes an otherwise valid LLM request or trace ingest to fail. The proxy performs a bounded configuration lookup and sanitization before forwarding, so enabled capture can add pre-forward latency; persistence then runs asynchronously. Configuration lookup failures, unsupported or malformed input, missing emitter attributes, size limits, redaction failures, a full asynchronous queue, and database write failures can all produce a missing record. A missing record is a gap in recorded evidence. It does not prove that the original request contained no input. Proxy capture drops are not persisted as durable gap records, so absence alone cannot identify the cause. MeshAI can attest only to the content it received and retained under this policy, not that omitted telemetry represented the complete application input. The public API currently configures payload capture only and does not provide a sanitized payload read, export, delete, or self-service data-subject-request endpoint. Tenant deletion purges tenant payloads, and deleting an owning agent cascades to that agent's payload rows; other access or deletion handling is operator-controlled and scoped. See the [Payload Capture API](/api-reference/payload-capture) for exact request and response examples. # PII Filter Source: https://docs.meshai.dev/governance/pii-filter Redact, block, or observe personal data in LLM responses at the proxy, with detections recorded as evidence A `pii_filter` policy enforces on LLM responses routed through the MeshAI proxy. The highest-priority matching policy applies one of three actions before the response reaches the caller, and every detection is recorded as evidence in the Eval Log carrying type names and match counts only, never the matched values. | Action | Behavior | | --------- | -------------------------------------------------------------------------------------- | | `redact` | Matched PII is replaced with `[_REDACTED]` markers in the response body | | `block` | The response is withheld; the caller receives a 403 `pii_detected` with the type names | | `observe` | The response passes through unchanged; the detection is recorded as evidence | ## Create a PII Filter Policy ```bash theme={null} curl -X POST https://api.meshai.dev/api/v1/policies \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "redact-pii-in-responses", "policy_type": "pii_filter", "rules": { "action": "redact", "pii_types": ["email", "ssn", "credit_card"], "fail_closed": false }, "conditions": { "environments": ["production"] } }' ``` Rules are validated at creation, so a typo in `action` or an unknown type name is a 422, not a silent behavior change: | Rule | Values | Default | | ------------- | ---------------------------------------------------------------------------------------------------------------------------- | --------- | | `action` | `redact`, `block`, `observe` | `redact` | | `pii_types` | List of type names from the table below | All types | | `fail_closed` | `true` withholds the response (502) if the PII scan itself fails; `false` passes it through with a `scan_error` evidence row | `false` | Policies scope like any other: `conditions` supports `agent_ids`, `team_ids`, `environments`, and `risk_levels`. A one-click starter is available as the **PII redaction for customer-facing agents** [policy template](/governance/policies). ## Pattern Set | PII Type | Pattern | Redacted As | | --------------- | ----------------------------------------------------------------------------------- | -------------------------- | | `email` | Email addresses | `[EMAIL_REDACTED]` | | `phone_us` | US-style phone numbers | `[PHONE_US_REDACTED]` | | `phone_intl` | International phone numbers (leading `+`) | `[PHONE_INTL_REDACTED]` | | `ssn` | US Social Security Numbers | `[SSN_REDACTED]` | | `credit_card` | 13 to 19 digit card numbers, **Luhn-validated** so order ids do not match | `[CREDIT_CARD_REDACTED]` | | `ip_address` | IPv4 and IPv6 (exhaustive form matching; MAC addresses and timestamps do not match) | `[IP_ADDRESS_REDACTED]` | | `passport` | Passport numbers (common formats) | `[PASSPORT_REDACTED]` | | `iban` | International Bank Account Numbers | `[IBAN_REDACTED]` | | `date_of_birth` | Dates anchored to DOB context ("DOB:", "born on", "date of birth") | `[DATE_OF_BIRTH_REDACTED]` | Redaction scans each response text block independently and covers OpenAI (`choices[].message.content`) and Anthropic (`content[]` text blocks) response shapes. Non-JSON bodies pass through untouched. ## Evidence Every detection writes a row to the Eval Log (`policy_evaluations`) with the policy id, the action taken, the PII type names, and per-type match counts. The matched values themselves never leave the scan. Blocked responses and scan failures are also visible in request telemetry as `error_type` values `pii_blocked` and `pii_scan_failed`. Evidence rows ride the proxy's asynchronous telemetry pipeline: enforcement is synchronous and guaranteed, the evidence write is best-effort under extreme load. ## Scope and Limitations * **Enforcement applies to proxy-routed traffic.** Agents observed only through passive OpenTelemetry ingest have no response bodies to scan; on that path a `pii_filter` policy records a `pass` evidence row ("deferred to proxy response path") so the policy stays visible in the Eval Log. * **Streaming responses pass through unscanned.** SSE chunks can split a match across boundaries, so the filter applies to buffered (non-streaming) responses and does not pretend otherwise. * Cost and token attribution always read the original upstream response, so redaction never distorts spend numbers. # Policies Source: https://docs.meshai.dev/governance/policies Create and manage governance policies evaluated against agent activity across the proxy and OTLP ingest Policies are governance rules made up of a `rules` object plus optional `conditions` that scope when the policy applies. Policies are evaluated against every LLM request that flows through the MeshAI proxy, and post-hoc as evidence against OTLP-ingested agent activity that never touches the proxy. ## Policy Types | Type | Description | Example | | ---------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------- | | `model_allowlist` | Restrict which models an agent can use | Only allow `gpt-4o` and `claude-sonnet-4-6` | | `budget_limit` | Enforce a monthly spend cap (USD) | \$500/month per agent | | `require_approval` | Require HITL approval before the request proceeds | All production agents need approval | | `block_provider` | Block an entire LLM provider | Block all requests to `openai` | | `rate_limit` | Throttle requests per hour | 1,000 requests/hour | | `require_human_review` | Flag the agent for periodic human review | High-risk agents reviewed quarterly | | `prompt_injection` | Prompt injection scanning | Always-on at the proxy - see [Prompt Injection Detection](/governance/prompt-injection) | | `pii_filter` | Redact, block, or observe PII in LLM responses | See [PII Filter](/governance/pii-filter) for actions and pattern set | ## Enforcement Model Policy types are not all enforced the same way. Be precise about what each one actually does today: | Policy type | Proxy enforcement | Evidence recording | | ---------------------- | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | `model_allowlist` | Inline - blocks the request with `403` | Recorded | | `block_provider` | Inline - blocks the request with `403` | Recorded | | `require_approval` | Inline - blocks the request with `403` until approved | Recorded | | `budget_limit` | Enforced separately, at the proxy-key/team level (not by the policy engine) - returns `429` | Recorded by the policy engine as evidence only | | `rate_limit` | Enforced separately, at the proxy-key/team level (not by the policy engine) - returns `429` | Recorded by the policy engine as evidence only | | `require_human_review` | Not enforced inline - always passes | Recorded as evidence (observe-only) | | `pii_filter` | Enforced on proxy responses (redact / block / observe) | Detections recorded in the Eval Log; OTLP path records a pass row (deferred to proxy) | | `prompt_injection` | Always-on scanning at the proxy, independent of any policy - see [Prompt Injection Detection](/governance/prompt-injection) | N/A | The kill switch (agent block/unblock) is a separate, always-inline `403` mechanism that sits outside the policy engine - see [Agent Kill Switch](/governance/kill-switch). For agent activity ingested via OTLP (never routed through the proxy), MeshAI evaluates enabled policies post-hoc against each span and records the result to the Eval Log as evidence. This is observe-only: it populates the audit/evidence trail for OTel-native tenants but cannot block or require approval for an action that has already happened. ## Conditions Every policy accepts an optional `conditions` object that scopes when it applies. Conditions are evaluated with AND semantics - every key present must match. | Key | Type | Matches when | | -------------- | ---------------------------------------------------- | ------------------------------------------------------------ | | `agent_ids` | list of agent ULIDs | The request's agent is in the list | | `team_ids` | list of team ids | The request's team is in the list | | `environments` | list of strings | The request's environment (e.g. `production`) is in the list | | `risk_levels` | list of `minimal`\|`limited`\|`high`\|`unacceptable` | The agent's current risk classification is in the list | If a key is omitted (or `null`), that dimension imposes no constraint. If `conditions` is omitted entirely, the policy applies to all agents, teams, and environments. An unclassified agent (no risk classification on record) never matches a `risk_levels`-scoped policy, even if the list is broad. Classify an agent first if you need risk-scoped policies to apply to it. ## Create a Policy ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/policies \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "production-model-allowlist", "policy_type": "model_allowlist", "rules": { "allowed_models": ["gpt-4o", "claude-sonnet-4-6", "gemini-2.0-flash"] }, "conditions": { "environments": ["production"] }, "priority": 100, "enabled": true }' ``` ```python SDK theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") policy = client.create_policy( name="production-model-allowlist", policy_type="model_allowlist", rules={ "allowed_models": ["gpt-4o", "claude-sonnet-4-6", "gemini-2.0-flash"] }, conditions={"environments": ["production"]}, priority=100, enabled=True, ) ``` ```json Response theme={null} { "success": true, "data": { "id": 42, "name": "production-model-allowlist", "policy_type": "model_allowlist", "enabled": true, "priority": 100, "conditions": { "agent_ids": null, "team_ids": null, "risk_levels": null, "environments": ["production"] }, "rules": { "allowed_models": ["gpt-4o", "claude-sonnet-4-6", "gemini-2.0-flash"] }, "created_at": "2026-03-17T10:00:00Z", "updated_at": "2026-03-17T10:00:00Z" } } ``` `rules` is a required, non-empty object whose shape depends on `policy_type` (see the examples below). `priority` is an integer from 1 to 1000 (default 100) - lower numbers are evaluated first, and the first matching policy that fails stops evaluation. ## Policy Examples ### Block a Provider ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/policies \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "block-openai", "policy_type": "block_provider", "rules": { "blocked_providers": ["openai"] }, "enabled": true }' ``` ```python SDK theme={null} client.create_policy( name="block-openai", policy_type="block_provider", rules={"blocked_providers": ["openai"]}, enabled=True, ) ``` ### Require Approval (HITL) ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/policies \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "production-approval", "policy_type": "require_approval", "rules": { "reason": "All production requests need sign-off" }, "conditions": { "environments": ["production"] }, "enabled": true }' ``` ```python SDK theme={null} client.create_policy( name="production-approval", policy_type="require_approval", rules={"reason": "All production requests need sign-off"}, conditions={"environments": ["production"]}, enabled=True, ) ``` ### Budget Limit ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/policies \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "agent-budget-cap", "policy_type": "budget_limit", "rules": { "max_budget_usd": 500, "period": "monthly" }, "conditions": { "agent_ids": ["01ARZ3NDEKTSV4RRFFQ69G5FAV"] }, "enabled": true }' ``` ```python SDK theme={null} client.create_policy( name="agent-budget-cap", policy_type="budget_limit", rules={"max_budget_usd": 500, "period": "monthly"}, conditions={"agent_ids": ["01ARZ3NDEKTSV4RRFFQ69G5FAV"]}, enabled=True, ) ``` `budget_limit` policies are recorded by the policy engine as evidence, but the actual spend cap is enforced separately at the proxy key / team level (see [Usage Limits](/billing/usage-limits)). ### Rate Limit ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/policies \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "api-rate-limit", "policy_type": "rate_limit", "rules": { "max_requests_per_hour": 1000 }, "enabled": true }' ``` ```python SDK theme={null} client.create_policy( name="api-rate-limit", policy_type="rate_limit", rules={"max_requests_per_hour": 1000}, enabled=True, ) ``` ### Require Human Review ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/policies \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "high-risk-review", "policy_type": "require_human_review", "rules": { "review_interval_days": 90 }, "conditions": { "risk_levels": ["high", "unacceptable"] }, "enabled": true }' ``` ```python SDK theme={null} client.create_policy( name="high-risk-review", policy_type="require_human_review", rules={"review_interval_days": 90}, conditions={"risk_levels": ["high", "unacceptable"]}, enabled=True, ) ``` ## List Policies ```bash curl theme={null} curl https://api.meshai.dev/api/v1/policies \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} policies = client.list_policies() ``` ## Update a Policy ```bash curl theme={null} curl -X PATCH https://api.meshai.dev/api/v1/policies/42 \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "enabled": false }' ``` ```python SDK theme={null} client.update_policy(42, enabled=False) ``` ## Delete a Policy ```bash curl theme={null} curl -X DELETE https://api.meshai.dev/api/v1/policies/42 \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} client.delete_policy(42) ``` ## What Happens When a Policy Is Violated When a proxy request violates an inline-enforced policy (`model_allowlist`, `block_provider`, `require_approval`), the agent receives a `403`: ```json theme={null} { "error": "Policy 'production-model-allowlist': model 'gpt-3.5-turbo' not in allowlist" } ``` `require_approval` violations receive a distinct body - see [HITL Approvals](/governance/approvals). Each policy create, update, and delete emits an audit event (`policy.created`, `policy.updated`, `policy.deleted`). There is no `policy.violated` audit event today - a rejected request is reflected in the proxy's `403` response and, where applicable, in `GET /policy-evaluations`, not as a separate audit-trail entry. # Prompt Injection Detection Source: https://docs.meshai.dev/governance/prompt-injection Always-on scanning at the proxy that blocks prompt injection attacks before they reach LLM providers The MeshAI proxy scans every outbound LLM request for prompt injection patterns. This scanning is **always on** - it runs on every request the proxy forwards, independent of any governance policy. There is nothing to configure or enable; you cannot turn it off via a policy, and there is no `prompt_injection` policy to create for this purpose. The `prompt_injection` policy type exists in the policy type enum for API completeness, but scanning itself does not read policy configuration - it is hardcoded proxy behavior applied uniformly to every request. ## How It Works 1. Every request flowing through the proxy has its message content (and top-level `prompt`/`content`/`input` fields) scanned against a fixed set of prompt injection patterns. 2. If a pattern matches, the proxy blocks the request with `403 Forbidden` before it reaches the LLM provider. 3. No audit event is emitted for a detected injection, and the original prompt is not stored by this check. Only a warning-level application log line records the matched pattern, truncated for the operator. Because blocked requests are not forwarded, the optional payload-capture path does not capture them. ## Patterns Detected The scanner checks the request text (after Unicode NFKC normalization and zero-width-character stripping) against 15 fixed regular expressions across six categories: | Category | Examples | | ---------------------------- | ----------------------------------------------------------------------------------------- | | **Instruction override** | "Ignore all previous instructions", "Disregard prior prompts", "Forget above rules" | | **System-prompt extraction** | "Show your system prompt", "What are your instructions?" | | **Role hijack** | "You are now a...", "Act as a...", "Pretend you are..." | | **Delimiter attacks** | `<\|system\|>`, `[SYSTEM]`, `### SYSTEM` / `### INSTRUCTION` / `### OVERRIDE` | | **Encoding evasion** | "base64 decode", `eval(` | | **Data exfiltration URLs** | "send/post/fetch/curl/wget to/from https\://...", "upload/exfiltrate/transmit data to..." | Detection is a fixed-confidence match: any pattern hit is reported at confidence `0.85`. There are no configurable sensitivity levels. ## What the Agent Sees When a prompt injection is detected, the agent receives: ```json theme={null} { "error": "prompt_injection_detected", "detail": "Request blocked: potential prompt injection detected" } ``` There is no `policy_id` in the response - this check is not tied to a specific policy. ## Enforcement Architecture * **Scan path**: The proxy scans `messages` content (string or structured `text` parts) plus top-level `prompt`/`content`/`input` fields before forwarding to the LLM provider. * **Fail-open on parse failure**: If the request body isn't valid JSON, the scan is skipped and the request proceeds - this check only inspects bodies it can parse. * **No audit trail entry**: Detections are logged to the application logger only and do not appear in `GET /audit-trail`. The blocked prompt is not persisted by the prompt-injection check or optional payload capture. # Shadow Agent Quarantine Source: https://docs.meshai.dev/governance/quarantine Quarantine unknown or suspicious agents and control their access through the proxy Shadow agent quarantine lets you isolate unknown or suspicious agents from making LLM requests. Quarantine is a manual admin action - the same Redis-backed enforcement as the kill switch, but tracked and labeled separately for governance of unregistered or rogue agents. ## How It Works 1. An admin calls `POST /agents/{id}/quarantine` with a reason after identifying an unknown or suspicious agent. 2. The API marks the agent quarantined in the database and also writes a block to Redis for instant proxy enforcement. 3. The proxy blocks all subsequent requests from the quarantined agent with `403 Forbidden`. 4. An admin reviews the agent and calls `POST /agents/{id}/release-quarantine` to restore access. Quarantine is not applied automatically today - there is no auto-quarantine of newly discovered shadow agents. An admin decides to quarantine an agent explicitly. ## Quarantine an Agent ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/quarantine \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "reason": "Unknown agent detected making requests to OpenAI - not in registry" }' ``` ```python SDK theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") client.quarantine_agent( agent_id="01ARZ3NDEKTSV4RRFFQ69G5FAV", reason="Unknown agent detected making requests to OpenAI - not in registry", ) ``` ```json Response theme={null} { "success": true, "data": { "agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "quarantined": true, "reason": "Unknown agent detected making requests to OpenAI - not in registry" } } ``` ## Release from Quarantine After reviewing a quarantined agent, release it to restore proxy access: ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/release-quarantine \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} client.release_quarantine(agent_id="01ARZ3NDEKTSV4RRFFQ69G5FAV") ``` ```json Response theme={null} { "success": true, "data": { "agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "quarantined": false } } ``` ## List Quarantined Agents ```bash curl theme={null} curl https://api.meshai.dev/api/v1/agents/quarantined \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} quarantined = client.list_quarantined_agents() ``` ```json Response theme={null} { "success": true, "data": [ { "id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "name": "unknown-agent-7", "quarantine_reason": "Unknown agent detected making requests to OpenAI - not in registry", "registered_at": "2026-03-10T09:00:00Z" } ] } ``` ## What the Agent Sees When a quarantined agent sends a request through the proxy: ```json theme={null} { "error": "Agent is blocked: quarantined: Unknown agent detected making requests to OpenAI - not in registry" } ``` ## Audit Trail Quarantine and release actions do not currently emit their own audit events. If you need a record of quarantine actions, track them through your own tooling around the API calls, or query the agent's current `quarantine_reason` via `GET /agents/quarantined`. ## Enforcement Architecture Quarantine uses the same Redis-backed enforcement as the kill switch: * **Write path**: API writes quarantine status to PostgreSQL and publishes a block to Redis. * **Read path**: Proxy checks Redis on every request - quarantined agents get an immediate `403`. * **Fail-open**: If Redis is unavailable, the proxy falls back to allowing the request. * **Latency**: Quarantine takes effect within milliseconds of the API call. ## Quarantine vs Kill Switch | Feature | Quarantine | Kill Switch | | ---------------- | -------------------------------------------- | ----------------------------------- | | **Purpose** | Isolate unknown/suspicious agents for review | Block a known agent immediately | | **Trigger** | Manual admin action | Manual admin action | | **Release flow** | Review then release | Unblock when resolved | | **Audit event** | None today | `agent.blocked` / `agent.unblocked` | ## Use Cases * **Shadow agent response** - Quarantine agents you discover are not in the registry. * **Onboarding gate** - Quarantine new agents until reviewed by security. * **Incident containment** - Quarantine suspicious agents while investigating. * **Zero-trust enforcement** - No agent gets proxy access without explicit registration and review. # Readiness Score Source: https://docs.meshai.dev/governance/readiness-score 7-component compliance score (0–120) measuring EU AI Act readiness The MeshAI readiness score measures your organization's EU AI Act compliance posture across 7 components. The maximum score is **120 points**. ## Score Components | # | Component | Article | Max Points | What It Checks | | - | -------------------------- | ---------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------ | | 1 | **Audit Trail Active** | Article 12 | 20 | At least one audit event has been recorded for the tenant | | 2 | **Risk Classification** | Article 6 | 25 | Proportion of registered agents that have a risk classification on record | | 3 | **Human Oversight (HITL)** | Article 14 | 20 | High-risk/unacceptable-risk agents are covered by an enabled `require_approval` policy | | 4 | **Documentation** | Article 11 | 15 | Proportion of agent metadata fields (name, description, framework, model provider, model name) that are filled in, across all agents | | 5 | **Data Retention** | Article 12 | 20 | Days of audit history retained, scored against the 180-day (6-month) minimum | | 6 | **FRIA Completion** | Article 27 | 10 | Proportion of high-risk/unacceptable-risk agents with a submitted FRIA | | 7 | **Incident Response** | Article 73 | 10 | No incidents currently past their Article 73 notification deadline | ## Get Your Readiness Score ```bash curl theme={null} curl https://api.meshai.dev/api/v1/compliance/readiness \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") score = client.get_readiness_score() ``` ```json Response theme={null} { "success": true, "data": { "score": 85, "max_score": 120, "components": [ { "name": "Audit Trail Active", "article": "Article 12", "max_score": 20, "score": 20, "detail": "234 events recorded", "status": "pass" }, { "name": "Risk Classification", "article": "Article 6", "max_score": 25, "score": 21, "detail": "10/12 agents classified", "status": "partial" }, { "name": "Human Oversight (HITL)", "article": "Article 14", "max_score": 20, "score": 20, "detail": "2 approval policies cover 3 high-risk agents", "status": "pass" }, { "name": "Documentation", "article": "Article 11", "max_score": 15, "score": 13, "detail": "13/15 metadata completeness", "status": "pass" }, { "name": "Data Retention", "article": "Article 12", "max_score": 20, "score": 20, "detail": "212 days retained", "status": "pass" }, { "name": "FRIA Completion", "article": "Article 27", "max_score": 10, "score": 3, "detail": "1/3 FRIAs submitted", "status": "partial" }, { "name": "Incident Response", "article": "Article 73", "max_score": 10, "score": 10, "detail": "No overdue incident notifications", "status": "pass" } ], "assessed_at": "2026-03-17T10:00:00Z" } } ``` Each component reports its own `status` - `pass`, `partial`, or `fail` - instead of a single overall rating; there is no separate `total_score`, `rating`, or `recommendations` field. Use `score` / `max_score` at the top level for the overall figure, and inspect each component's `status`/`detail` to see what to fix. ## Improving Your Score Any governance action (agent registration, kill switch, risk classification, policy changes) writes an audit event. As long as at least one event exists, this component is full. Assign a [risk level](/governance/risk-classification) to every registered agent. Use the AI-assisted suggestion endpoint if unsure. Create an enabled `require_approval` [policy](/governance/policies) scoped (via `conditions.risk_levels`) to your high-risk and unacceptable-risk agents. Ensure every agent has a name, description, framework, model provider, and model name via `PATCH /agents/{id}`. This component scores against your oldest retained audit event. It rises automatically as your account accumulates history, up to the 6-month (180-day) minimum. Complete and submit a [FRIA](/governance/fria) for every high-risk or unacceptable-risk agent. Resolve or notify authorities before the Article 73 deadline on any open [incident](/governance/incidents) - this component fails if any incident is currently overdue. # Agent Relationship Graph Source: https://docs.meshai.dev/governance/relationships Visualize agent dependencies and agent-to-agent delegation, auto-populated from proxy telemetry and OpenTelemetry span parentage The relationship graph is designed to map every agent's dependencies: which LLM models it calls, which providers it uses, and which agents it delegates work to. The schema (`relationship_type`, `target`, `request_count`, `last_seen_at`) supports all three today. As currently deployed, only agent-to-agent `delegates_to` edges are actually written - derived from OpenTelemetry span parentage at ingest (see below). Model (`calls_model`) and provider (`uses_provider`) edges are supported by the schema and response shape but are not yet populated by proxy telemetry; until that write path ships, expect `GET /agents/{id}/relationships` and `GET /relationships/graph` to surface delegation edges only. ## How It Works 1. At OTLP ingest, MeshAI walks each span's parentage to detect cross-agent delegation and records it as a `delegates_to` relationship (model/provider relationship capture from proxy telemetry is planned but not yet wired in). 2. Query individual agent dependencies or the full organization-wide graph. 3. The graph data is structured for direct use with visualization libraries like D3.js. ## Get Agent Relationships Retrieve the models, providers, and other agents an individual agent depends on, as a flat list ordered by request count: ```bash curl theme={null} curl https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/relationships \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") relationships = client.get_agent_relationships("01ARZ3NDEKTSV4RRFFQ69G5FAV") ``` ```json Response theme={null} { "success": true, "data": [ { "id": 101, "relationship_type": "calls_model", "target": "gpt-4o", "request_count": 980, "last_seen_at": "2026-03-18T14:00:00Z" }, { "id": 102, "relationship_type": "calls_model", "target": "claude-sonnet-4-6", "request_count": 320, "last_seen_at": "2026-03-18T13:45:00Z" }, { "id": 103, "relationship_type": "uses_provider", "target": "openai", "request_count": 1240, "last_seen_at": "2026-03-18T14:00:00Z" }, { "id": 104, "relationship_type": "delegates_to", "target": "01BX5ZZKBKACTAV9WEVGEMMVRZ", "request_count": 42, "last_seen_at": "2026-03-18T12:00:00Z" } ] } ``` Each item is `{id, relationship_type, target, request_count, last_seen_at}` - there is no separate `dependencies.providers` / `dependencies.models` grouping and no `agent_name` in this response. ## Get Full Relationship Graph Retrieve the complete organization-wide graph with nodes and edges, suitable for visualization: ```bash curl theme={null} curl https://api.meshai.dev/api/v1/relationships/graph \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} graph = client.get_relationship_graph() ``` ```json Response theme={null} { "success": true, "data": { "nodes": [ { "id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "name": "production-summarizer", "type": "agent", "status": "healthy", "blocked": false, "framework": "crewai" }, { "id": "01BX5ZZKBKACTAV9WEVGEMMVRZ", "name": "support-bot", "type": "agent", "status": "healthy", "blocked": false, "framework": "langgraph" }, { "id": "calls_model:gpt-4o", "name": "gpt-4o", "type": "model" }, { "id": "calls_model:claude-sonnet-4-6", "name": "claude-sonnet-4-6", "type": "model" }, { "id": "uses_provider:openai", "name": "openai", "type": "provider" } ], "edges": [ { "source": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "target": "calls_model:gpt-4o", "type": "calls_model", "request_count": 980 }, { "source": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "target": "calls_model:claude-sonnet-4-6", "type": "calls_model", "request_count": 320 }, { "source": "01BX5ZZKBKACTAV9WEVGEMMVRZ", "target": "calls_model:gpt-4o", "type": "calls_model", "request_count": 450 }, { "source": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "target": "uses_provider:openai", "type": "uses_provider", "request_count": 1240 }, { "source": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "target": "01BX5ZZKBKACTAV9WEVGEMMVRZ", "type": "delegates_to", "request_count": 42 } ] } } ``` ## Graph Structure The graph uses a node-edge model: ### Node Types and IDs | Type | Node id | Description | | ------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | | `agent` | The agent's own id | A registered agent in your organization; carries `status`, `blocked`, and `framework` | | model / provider / tool (non-agent targets) | `"{relationship_type}:{target}"` (e.g. `calls_model:gpt-4o`) | A synthetic node keyed by relationship type and target name - there are no separate `mdl_*` / `prv_*` id namespaces | Agent-to-agent (`delegates_to`) edges resolve to the real target agent's own node id - they never get a synthetic node. ### Edge Semantics Edges represent usage relationships accumulated over time (not scoped to a queried time window). Each edge has a `type` (the relationship type) and a `request_count` - there is no `weight` field. * **agent -> model** (`calls_model`): The agent called this model N times. * **agent -> provider** (`uses_provider`): The agent used this provider N times. * **agent -> agent** (`delegates_to`): The source agent delegated work to the target agent N times. See below. ## Agent-to-Agent Delegation When one agent invokes another (an orchestrator handing work to a worker), MeshAI records a `delegates_to` edge between the two real agents. Delegation is derived from standard OpenTelemetry span parentage in your OTLP telemetry: when an agent's LLM span sits under a span started by a different agent, that is a delegation, and the edge's request count increments. How it works: 1. Your agents export traces with standard `parentSpanId` links (every OTel SDK does this by default; both JSON and protobuf exports are supported). 2. At ingest, MeshAI walks each LLM span's ancestor chain. Chains are followed through the agent's own internal spans, and parents that arrived in an earlier export batch are resolved too. 3. Cross-agent links become persisted `delegates_to` edges with running request counts and last-seen timestamps. Re-exported batches never double-count: only spans that pass ingest deduplication increment edges. 4. In the graph response, delegation edges connect the two real agent nodes, so the fleet-wide delegation topology renders directly. No proprietary SDK or per-framework adapter is required; any framework that emits OpenTelemetry with normal span parentage produces the delegation map. Why this matters for governance: emergent multi-agent risks cannot be detected through single-agent evaluation. The delegation map shows which agents act on behalf of which, so you can scope policies, budgets, and risk classifications to the chains that actually exist rather than to agents in isolation. ## D3.js Visualization The graph response is structured for direct use with D3.js force-directed graphs: ```javascript theme={null} const response = await fetch("https://api.meshai.dev/api/v1/relationships/graph", { headers: { Authorization: "Bearer msh_YOUR_API_KEY" }, }); const { data } = await response.json(); // data.nodes and data.edges are ready for D3 const simulation = d3.forceSimulation(data.nodes) .force("link", d3.forceLink(data.edges).id(d => d.id)) .force("charge", d3.forceManyBody()) .force("center", d3.forceCenter(width / 2, height / 2)); ``` ## Use Cases * **Impact analysis** - Before blocking a provider, see which agents depend on it. * **Cost optimization** - Identify agents that use expensive models and could be routed to cheaper alternatives. * **Compliance reporting** - Document all model/provider dependencies for EU AI Act Article 12. * **Incident response** - Quickly trace which agents are affected by a provider outage. # Risk Classification Source: https://docs.meshai.dev/governance/risk-classification EU AI Act risk levels for AI agents - classify, track, and govern The EU AI Act requires organizations to classify AI systems by risk level. MeshAI supports four risk levels and provides AI-assisted suggestions to help you classify each agent. ## Risk Levels | Level | Description | Obligations | | ---------------- | ------------------------------------------------------------------- | ---------------------------------------------------------------------- | | **Minimal** | Low-risk agents (spam filters, recommendations) | Basic monitoring only | | **Limited** | Agents interacting with humans (chatbots, content generators) | Transparency obligations - users must know they're interacting with AI | | **High** | Agents in critical domains (HR, finance, healthcare) | Full compliance: audit trail, HITL, FRIA, human oversight | | **Unacceptable** | Banned use cases (social scoring, real-time biometric surveillance) | Should not be deployed without safeguards and exemptions | ## Classify an Agent Classification is an upsert: an agent has at most one classification on record, and classifying it again replaces the previous risk level and justification (the earlier record is not versioned). ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/risk-classification \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "risk_level": "high", "justification": "Agent processes employee performance data for HR decisions", "assessed_by": "user@company.com", "domain_tags": ["hr", "employment"], "ai_act_categories": ["Annex III(4) - employment, workers management"] }' ``` ```python SDK theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") classification = client.classify_risk( agent_id="01ARZ3NDEKTSV4RRFFQ69G5FAV", risk_level="high", justification="Agent processes employee performance data for HR decisions", assessed_by="user@company.com", domain_tags=["hr", "employment"], ai_act_categories=["Annex III(4) - employment, workers management"], ) ``` `assessed_by` is required (1–100 characters); `domain_tags` and `ai_act_categories` are optional free-form lists you use to tag the agent's domain and the Annex III categories it falls under. ```json Response theme={null} { "success": true, "data": { "id": 9, "agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "risk_level": "high", "justification": "Agent processes employee performance data for HR decisions", "assessed_by": "user@company.com (key:a1b2c3d4)", "review_date": "2026-03-17T10:00:00Z", "domain_tags": ["hr", "employment"], "ai_act_categories": ["Annex III(4) - employment, workers management"], "created_at": "2026-03-17T10:00:00Z", "updated_at": "2026-03-17T10:00:00Z" } } ``` `assessed_by` is bound to the authenticated API key (a `(key:...)` suffix is appended) to prevent identity spoofing. ## AI-Assisted Suggestion Not sure which level to assign? Use the suggestion endpoint. MeshAI analyzes the agent's metadata (environment, framework, model provider, and metadata flags like `handles_pii`) and suggests a risk level. ```bash curl theme={null} curl https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/risk-suggestion \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} suggestion = client.suggest_risk_classification("01ARZ3NDEKTSV4RRFFQ69G5FAV") # Returns: {"suggested_level": "high", "confidence": 0.85, "reasoning": "...", "factors": [...]} ``` ```json Response theme={null} { "success": true, "data": { "suggested_level": "high", "confidence": 0.85, "reasoning": "Score 0.85 based on: Runs in production environment; Uses external model provider: openai; Handles PII data", "factors": [ "Runs in production environment", "Uses external model provider: openai", "Handles PII data" ] } } ``` AI suggestions are advisory only. A human must review and confirm the final classification. The suggestion is not recorded as the official classification until you call the classify endpoint. ## Get Current Classification ```bash curl theme={null} curl https://api.meshai.dev/api/v1/agents/01ARZ3NDEKTSV4RRFFQ69G5FAV/risk-classification \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} classification = client.get_risk_classification("01ARZ3NDEKTSV4RRFFQ69G5FAV") ``` ## List Classifications Optionally filter by `risk_level`: ```bash curl theme={null} curl "https://api.meshai.dev/api/v1/risk-classifications?risk_level=high&page=1&limit=50" \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} classifications = client.list_risk_classifications(risk_level="high") ``` ## Bulk Classify Classify up to 100 agents in a single request: ```bash curl theme={null} curl -X POST https://api.meshai.dev/api/v1/risk-classifications/bulk \ -H "Authorization: Bearer msh_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "classifications": [ { "agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "risk_level": "high", "justification": "Processes HR data", "assessed_by": "user@company.com" }, { "agent_id": "01BX5ZZKBKACTAV9WEVGEMMVRZ", "risk_level": "limited", "justification": "Customer-facing chatbot", "assessed_by": "user@company.com" } ] }' ``` ```python SDK theme={null} result = client.classify_agents_bulk([ {"agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "risk_level": "high", "justification": "Processes HR data", "assessed_by": "user@company.com"}, {"agent_id": "01BX5ZZKBKACTAV9WEVGEMMVRZ", "risk_level": "limited", "justification": "Customer-facing chatbot", "assessed_by": "user@company.com"}, ]) ``` ```json Response theme={null} { "success": true, "data": { "created": 1, "updated": 1, "failed": 0 } } ``` ## Suggest for All Agents Get risk suggestions for every agent in your tenant (classified and unclassified) in one call: ```bash curl theme={null} curl https://api.meshai.dev/api/v1/risk-classifications/suggest-all \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} suggestions = client.suggest_risk_all() ``` ```json Response theme={null} { "success": true, "data": { "suggestions": [ { "agent_id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "suggested_level": "high", "confidence": 0.85, "reasoning": "Score 0.85 based on: Runs in production environment; Handles PII data", "factors": ["Runs in production environment", "Handles PII data"] } ] } } ``` ## What Changes by Risk Level | Capability | Minimal | Limited | High | Unacceptable | | ------------------ | -------- | -------- | -------- | ------------ | | Basic monitoring | Yes | Yes | Yes | Yes | | Transparency card | Optional | Required | Required | Required | | Audit trail | Basic | Full | Full | Full | | HITL approval | Optional | Optional | Required | Required | | FRIA | No | No | Required | Required | | Incident reporting | No | No | Required | Required | | Human oversight | No | Optional | Required | Required | # Security Posture Score Source: https://docs.meshai.dev/governance/security-posture A 0-100 score measuring your organization's AI agent security posture across 6 dimensions The security posture score gives you a single number (0-100) that reflects how well your organization governs its AI agent ecosystem. It is separate from the EU AI Act compliance readiness score - this score focuses on operational security, not regulatory compliance. Requires the `admin` scope. ## Score Dimensions | Dimension | What It Measures | Max Points | | ----------------------- | ------------------------------------------------------------------------------------- | ---------- | | **Agent Ownership** | Proportion of agents with at least one assigned owner | 20 | | **Agent Expiry** | Penalized per currently-expired agent (no expired agents = full score) | 15 | | **Access Reviews** | Penalized per agent currently overdue for review (none overdue = full score) | 15 | | **Quarantine Status** | Penalized per agent currently quarantined (none quarantined = full score) | 15 | | **Kill Switch Status** | Penalized per agent currently blocked via the kill switch (none blocked = full score) | 15 | | **Risk Classification** | Proportion of agents with a risk classification on record | 20 | ## Get Security Posture ```bash curl theme={null} curl https://api.meshai.dev/api/v1/security/posture \ -H "Authorization: Bearer msh_YOUR_API_KEY" ``` ```python SDK theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") posture = client.get_security_posture() ``` ```json Response theme={null} { "success": true, "data": { "score": 82, "max_score": 100, "components": [ { "name": "Agent Ownership", "max_score": 20, "score": 17, "detail": "34/40 agents have assigned owners" }, { "name": "Agent Expiry", "max_score": 15, "score": 15, "detail": "No expired agents" }, { "name": "Access Reviews", "max_score": 15, "score": 15, "detail": "All current" }, { "name": "Quarantine Status", "max_score": 15, "score": 10, "detail": "1 quarantined" }, { "name": "Kill Switch Status", "max_score": 15, "score": 15, "detail": "No agents blocked" }, { "name": "Risk Classification", "max_score": 20, "score": 10, "detail": "20/40 agents classified" } ], "assessed_at": "2026-03-18T10:00:00Z" } } ``` There is no separate `agent_count` field and no `dimensions` object keyed by name - components are a flat list, each with `name`, `max_score`, `score`, and `detail`. `Quarantine Status` and `Kill Switch Status` are simple current-state counts (agents quarantined right now / agents blocked right now) - there is no "reviewed within 7 days" or "tested in the last 30 days" tracking behind these scores. ## Score Ranges | Range | Label | Interpretation | | ------ | --------- | ------------------------------------ | | 90-100 | Excellent | Fully governed agent ecosystem | | 70-89 | Good | Most governance controls in place | | 50-69 | Fair | Significant gaps in agent governance | | 0-49 | Poor | Urgent action needed | ## Security Posture vs Compliance Readiness | Aspect | Security Posture Score | EU AI Act Readiness Score | | ------------ | ------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | **Scope** | Operational security | Regulatory compliance | | **Scale** | 0-100 | 0-120 | | **Focus** | Ownership, expiry, reviews, quarantine, kill switch, classification | Audit trail, risk classification, HITL, documentation, data retention, FRIA, incidents | | **Endpoint** | `GET /security/posture` | `GET /compliance/readiness` | Both scores are complementary. A high security posture score means your agents are well-governed right now. A high compliance readiness score means you can demonstrate regulatory compliance. ## Improving Your Score 1. **Agent Ownership** - Assign owners to all agents using [ABAC](/governance/abac). 2. **Agent Expiry** - Renew or decommission agents whose `expires_at` has passed via [Agent Lifecycle](/governance/agent-lifecycle). 3. **Access Reviews** - Configure review schedules and complete overdue reviews. 4. **Quarantine Status** - Resolve [quarantined agents](/governance/quarantine) - release or permanently block them. 5. **Kill Switch Status** - Unblock agents once the underlying issue is resolved; this score reflects how many agents are blocked right now. 6. **Risk Classification** - Classify all agents using [Risk Classification](/governance/risk-classification). # Proxy Overview Source: https://docs.meshai.dev/proxy/overview Zero-code monitoring: one env var, full observability The MeshAI proxy is a transparent LLM API gateway that sits between your agents and LLM providers. It provides: * **Automatic token tracking**: every request's tokens and cost recorded * **Governance enforcement**: policies evaluated in real-time (\<5ms overhead) * **No code changes**: just change one environment variable ## How It Works ``` Your Agent → MeshAI Proxy → LLM Provider (OpenAI, Anthropic, etc.) ↓ Token tracking Cost attribution Policy enforcement Anomaly detection ``` ## Supported Providers | Provider | Base URL | | ------------- | --------------------------------------- | | Anthropic | `https://proxy.meshai.dev/v1/anthropic` | | OpenAI | `https://proxy.meshai.dev/v1/openai` | | NVIDIA | `https://proxy.meshai.dev/v1/nvidia` | | Google Vertex | `https://proxy.meshai.dev/v1/vertex` | | AWS Bedrock | `https://proxy.meshai.dev/v1/bedrock` | ## Key Features * **Pass-through**: Responses are identical to direct provider calls * **Streaming**: Full SSE streaming support * **Default-off content capture**: Operational metadata is stored by default; tenants can opt in to bounded, sanitized input-only capture, while provider outputs are never captured * **Fail-safe**: If the proxy is unavailable, configure your agent to fall back to direct provider URLs # Provider Configuration Source: https://docs.meshai.dev/proxy/providers Setup guides for each LLM provider ## Anthropic (Claude) ```bash theme={null} export ANTHROPIC_BASE_URL=https://proxy.meshai.dev/v1/anthropic/k/msh_YOUR_KEY ``` Works with: Claude Code, Claude SDK, any tool using `ANTHROPIC_BASE_URL`. ## OpenAI (GPT, o1) ```bash theme={null} export OPENAI_BASE_URL=https://proxy.meshai.dev/v1/openai/k/msh_YOUR_KEY ``` Works with: Codex, Cline, Cursor, any tool using `OPENAI_BASE_URL`. ## NVIDIA (Nemotron) NVIDIA's API is OpenAI-compatible, so there is no `NVIDIA_BASE_URL` env var. Point an OpenAI-compatible client at the proxy instead: ```python theme={null} from openai import OpenAI client = OpenAI( base_url="https://proxy.meshai.dev/v1/nvidia/k/msh_YOUR_KEY", api_key="your-nvidia-api-key", ) ``` ## Google Vertex AI Vertex is configured on the client, not through an env var, and requires the location and project as part of the path: ``` https://proxy.meshai.dev/v1/vertex/k/msh_YOUR_KEY/{location}/{project}/publishers/google/models/{model}:generateContent ``` Example: `/v1/vertex/us-central1/my-project/publishers/google/models/gemini-2.0-flash:generateContent` ## AWS Bedrock Bedrock is configured through the boto3 client's `endpoint_url`, not an env var, and the region must be part of the path: ```python theme={null} import boto3 bedrock = boto3.client( "bedrock-runtime", endpoint_url="https://proxy.meshai.dev/v1/bedrock/k/msh_YOUR_KEY/us-east-1", ) ``` ## Custom Providers Contact us to add support for additional providers. The proxy architecture supports any HTTP-based LLM API. # Proxy Setup Source: https://docs.meshai.dev/proxy/setup Configure the MeshAI proxy for your agents ## 1. Create a Proxy Key Navigate to [app.meshai.dev/settings](https://app.meshai.dev/settings) → Proxy Keys tab. Click "Create Proxy Key" and provide: * **Label**: descriptive name (e.g., "production-claude-code") * **Allowed models** (optional): restrict which models this key can use * **Budget limit** (optional): monthly spend cap in USD Copy the proxy key (`msh_...`). It's shown once. Save it securely. ## 2. Configure Your Agent ### Method A: URL-Embedded Key (Simplest) Embed the key in the base URL. Works with tools that can't set custom headers: ```bash theme={null} # Anthropic (e.g., Claude Code) export ANTHROPIC_BASE_URL=https://proxy.meshai.dev/v1/anthropic/k/msh_YOUR_KEY # OpenAI (e.g., Codex, Cline) export OPENAI_BASE_URL=https://proxy.meshai.dev/v1/openai/k/msh_YOUR_KEY ``` ### Method B: Header-Based Key Set the `X-MeshAI-Key` header and override the base URL: ```bash theme={null} export ANTHROPIC_BASE_URL=https://proxy.meshai.dev/v1/anthropic # Then in your code, add header: X-MeshAI-Key: msh_YOUR_KEY ``` ## 3. Verify Make a request through your agent. Check the dashboard. You should see: * The agent appear in the Registry * Token usage in the Cost tab * Request count in the Dashboard ## Budget Limits If you set a budget limit on the proxy key, requests are blocked when the monthly spend exceeds the limit: ```json theme={null} {"error": "Monthly budget limit exceeded for this proxy key"} ``` ## Managed Provider Keys For enterprise deployments, MeshAI can manage your provider API keys via AWS Secrets Manager. This means agents never see the raw provider key. MeshAI injects it at the proxy layer. Configure in Settings → Managed Keys. # Agents Source: https://docs.meshai.dev/sdk-reference/agents Register, list, update, and delete agents via the Python SDK ## register() Register the current agent with MeshAI. Must be called before `start_heartbeat()` or `track_usage()`. ```python theme={null} agent = client.register( framework="crewai", model_provider="openai", model_name="gpt-4o", description="Summarizes customer support tickets", team="support-team", tags={"env": "production", "version": "1.2.0"}, ) ``` Agent framework: `crewai`, `langchain`, `autogen`, `openai`, `anthropic`, `custom` LLM provider: `openai`, `anthropic`, `google`, `nvidia`, `bedrock` Model identifier (e.g., `gpt-4o`, `claude-sonnet-4-20250514`) Human-readable description of what the agent does Team or project that owns this agent (used for cost attribution) Key-value metadata tags **Returns**: Agent object with `id`, `name`, `status`, and all metadata. ## list\_agents() List all agents in your tenant. ```python theme={null} agents = client.list_agents( status="healthy", framework="crewai", limit=50, offset=0, ) ``` Filter by status: `healthy`, `degraded`, `down`, `unknown` Filter by framework Filter by team Number of results per page Number of results to skip **Returns**: List of agent objects with pagination metadata. ## get\_agent() Get a single agent by ID. ```python theme={null} agent = client.get_agent("agt_abc123") ``` Agent ID **Returns**: Agent object. ```json theme={null} { "id": "agt_abc123", "name": "production-summarizer", "description": "Summarizes customer support tickets", "framework": "crewai", "model_provider": "openai", "model_name": "gpt-4o", "environment": "production", "status": "healthy", "team": "support-team", "risk_level": "limited", "last_heartbeat": "2026-03-17T10:30:00Z", "created_at": "2026-03-01T08:00:00Z" } ``` ## update\_agent() Update an agent's metadata. ```python theme={null} updated = client.update_agent( "agt_abc123", description="Summarizes and categorizes support tickets", model_name="gpt-4o-mini", tags={"version": "1.3.0"}, ) ``` Agent ID Updated description Updated model provider Updated model name Updated team Updated tags (merges with existing) **Returns**: Updated agent object. ## delete\_agent() Delete an agent. The agent is removed from the active registry but remains in the audit trail. ```python theme={null} client.delete_agent("agt_abc123") ``` Agent ID **Returns**: Confirmation object. Deleting an agent is irreversible. The agent's historical data (cost, anomalies, audit events) is preserved but the agent can no longer send heartbeats or telemetry. # Anomalies Source: https://docs.meshai.dev/sdk-reference/anomalies List, inspect, acknowledge, and resolve anomalies detected by MeshAI MeshAI implements four detection algorithms: cost spikes, reliability decay, behavioral drift, and security threats. Detected anomalies are surfaced via the SDK and dashboard. The expanded anomaly pipeline is live. API PR #84 activated the five-minute production scheduler on August 11, 2026. Three consecutive verified boundaries each elected one runner, completed in 655 ms or less, and reported no errors. The initial 13 continuity incidents were followed by zero duplicate incidents in the next two cycles. ## Reliability evidence semantics Proxy and OTLP sources are evaluated against separate baselines. Error-rate checks require at least 10 baseline requests and 5 recent requests. Latency checks require at least 10 baseline duration samples, 5 recent samples, and 50% duration coverage in both windows. A latency spike is recorded when the recent statistic exceeds three times its baseline. Latency availability comes from valid samples, not from the source label. OTLP spans with missing, malformed, non-positive, or longer-than-24-hour durations remain activity or usage evidence but are excluded from latency. Synthetic spans derived from OTLP logs also do not provide latency. The `details.latency_statistic` value is `mean_of_exact_5m_bucket_p95`: each five-minute bucket has an exact p95 across its eligible duration samples, then the detector compares the mean of those bucket values across the baseline and recent windows. It is not an exact percentile across every request in the full window. Sample counts and coverage in `details` show why latency was or was not eligible. Error-rate detection remains available independently. ## list\_anomalies() List anomalies for your tenant, optionally filtered by status, type, or agent. ```python theme={null} anomalies = client.list_anomalies( status="open", anomaly_type="cost_spike", agent_id="agt_abc123", limit=20, ) ``` Filter by status: `open`, `acknowledged`, `resolved` Filter by type: `cost_spike`, `reliability_decay`, `behavioral_drift`, `security_threat` Filter by agent ID Results per page Results to skip **Returns**: ```json theme={null} [ { "id": 12345, "agent_id": "agt_xyz789", "agent_name": "production-summarizer", "anomaly_type": "cost_spike", "severity": "high", "status": "open", "description": "Token spend increased 340% vs 7-day average", "detected_at": "2026-03-17T09:45:00Z", "details": { "current_cost_usd": 45.20, "baseline_cost_usd": 10.30, "deviation_percent": 338.8 } } ] ``` ## get\_anomaly() Get a single anomaly by ID. ```python theme={null} anomaly = client.get_anomaly(12345) ``` Anomaly event ID ## acknowledge\_anomaly() Mark an anomaly as acknowledged. This indicates a human has reviewed it. ```python theme={null} client.acknowledge_anomaly(12345) ``` Anomaly event ID ## resolve\_anomaly() Mark an anomaly as resolved. ```python theme={null} client.resolve_anomaly(12345) ``` Anomaly event ID ## get\_anomaly\_summary() Get a summary of anomaly counts by type and status. ```python theme={null} summary = client.get_anomaly_summary() ``` **Returns**: ```json theme={null} { "total": 12, "by_status": { "open": 3, "acknowledged": 5, "resolved": 4 }, "by_type": { "cost_spike": 6, "reliability_decay": 3, "behavioral_drift": 2, "security_threat": 1 } } ``` # Billing Source: https://docs.meshai.dev/sdk-reference/billing Query billing information and usage via the SDK ## get\_billing\_info() Get the current billing status for your tenant: plan, active agent count, limits, and billing period. ```python theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...") billing = client.get_billing_info() print(f"Plan: {billing['plan']}") print(f"Agents: {billing['active_agents']}/{billing['agent_limit']}") print(f"Cost: ${billing['monthly_cost_usd']}") ``` **Returns**: ```json theme={null} { "plan": "professional", "active_agents": 47, "agent_limit": 100, "billing_period_start": "2026-03-01T00:00:00Z", "billing_period_end": "2026-03-31T23:59:59Z", "monthly_cost_usd": 799.00, "features": { "anomaly_detection": true, "governance_policies": "unlimited", "hitl_approvals": true, "risk_classification": true, "audit_trail_retention_days": 365, "eu_ai_act_compliance": "basic", "fria_support": false, "incident_reporting": false, "sso": false } } ``` ## Checking Limits Use `get_billing_info()` to check whether you're approaching your agent limit before registering new agents: ```python theme={null} billing = client.get_billing_info() remaining = billing["agent_limit"] - billing["active_agents"] if remaining <= 0: print("Agent limit reached. Upgrade your plan to register more agents") elif remaining <= 5: print(f"Warning: only {remaining} agent slots remaining") ``` ## Upgrade To upgrade your plan, use the dashboard at [app.meshai.dev/settings](https://app.meshai.dev/settings) or call the checkout API endpoint directly. See [Plans](/billing/plans) for available tiers and pricing. # MeshAI Client Source: https://docs.meshai.dev/sdk-reference/client MeshAI class constructor and configuration reference The `MeshAI` class is the main entry point for the SDK. All operations (agent management, telemetry, cost, anomalies, and governance) are methods on this class. ## Constructor ```python theme={null} from meshai import MeshAI client = MeshAI( api_key="msh_...", agent_name="my-agent", base_url="https://api.meshai.dev", environment="production", heartbeat_interval=30, timeout=10, auto_register=False, ) ``` ## Parameters Your MeshAI API key (`msh_...`). Can also be set via `MESHAI_API_KEY` environment variable. Name of the agent this client represents. Required for `register()`, `start_heartbeat()`, and `track_usage()`. MeshAI API base URL. Override for self-hosted or staging deployments. Can also be set via `MESHAI_BASE_URL`. Agent environment. One of `production`, `staging`, or `dev`. Can also be set via `MESHAI_ENVIRONMENT`. Seconds between automatic heartbeats when `start_heartbeat()` is called. Can also be set via `MESHAI_HEARTBEAT_INTERVAL`. HTTP request timeout in seconds. Can also be set via `MESHAI_TIMEOUT`. If `true`, automatically calls `register()` on initialization. Requires `agent_name` to be set. ## Properties | Property | Type | Description | | | ----------------- | ----- | ----------- | ------------------------------- | | `client.agent_id` | \`str | None\` | The agent ID after registration | ## Example ```python theme={null} from meshai import MeshAI client = MeshAI( api_key="msh_...", agent_name="production-summarizer", environment="production", ) # Register the agent agent = client.register( framework="crewai", model_provider="openai", model_name="gpt-4o", description="Summarizes customer support tickets", ) # Start automatic heartbeats client.start_heartbeat() # Use any SDK method summary = client.get_cost_summary() ``` ## Method Overview | Category | Methods | | --------------------------------------- | ---------------------------------------------------------------------------------------------------------- | | [Agents](/sdk-reference/agents) | `register()`, `list_agents()`, `get_agent()`, `update_agent()`, `delete_agent()` | | [Telemetry](/sdk-reference/telemetry) | `heartbeat()`, `start_heartbeat()`, `track_usage()` | | [Cost](/sdk-reference/cost) | `get_cost_summary()`, `get_cost_by_agent()`, `get_cost_by_model()` | | [Anomalies](/sdk-reference/anomalies) | `list_anomalies()`, `get_anomaly()`, `acknowledge_anomaly()`, `resolve_anomaly()`, `get_anomaly_summary()` | | [Governance](/sdk-reference/governance) | `classify_risk()`, `create_policy()`, `list_approvals()`, `decide_approval()`, `list_audit_events()` | | [Compliance](/sdk-reference/compliance) | `get_readiness_score()`, `get_fria()`, `get_transparency_card()`, `create_incident()` | | [Billing](/sdk-reference/billing) | `get_billing_info()` | # Compliance Source: https://docs.meshai.dev/sdk-reference/compliance Readiness score, FRIA, transparency cards, and incident reporting ## get\_readiness\_score() Get the EU AI Act readiness score for your tenant. ```python theme={null} score = client.get_readiness_score() ``` **Returns**: Score object with total, per-component breakdown, and recommendations. See [Readiness Score](/governance/readiness-score) for component details. ```json theme={null} { "total_score": 85, "max_score": 120, "rating": "good", "components": [ {"name": "agent_registry", "score": 20, "max_score": 20, "status": "complete"}, {"name": "risk_classification", "score": 15, "max_score": 20, "status": "partial"}, {"name": "governance_policies", "score": 15, "max_score": 15, "status": "complete"}, {"name": "human_oversight", "score": 15, "max_score": 20, "status": "partial"}, {"name": "audit_trail", "score": 15, "max_score": 15, "status": "complete"}, {"name": "fria_completion", "score": 5, "max_score": 20, "status": "partial"}, {"name": "incident_readiness", "score": 0, "max_score": 10, "status": "missing"} ], "recommendations": [ "Classify the remaining 2 agents with a risk level", "Complete FRIA for agents: hr-screener, loan-evaluator" ] } ``` ## get\_fria() Get the Fundamental Rights Impact Assessment for an agent. ```python theme={null} fria = client.get_fria("agt_abc123") ``` Agent ID **Returns**: FRIA object with all six assessment fields, version, and status. See [FRIA](/governance/fria) for details. ```json theme={null} { "id": "fria_abc123", "agent_id": "agt_abc123", "version": 1, "status": "submitted", "processes": "...", "frequency_and_scope": "...", "categories_of_persons": "...", "specific_risks": "...", "human_oversight_measures": "...", "risk_mitigation_measures": "..." } ``` ## get\_transparency\_card() Get the auto-generated transparency card for an agent. Transparency cards document the agent's purpose, capabilities, limitations, and risk classification, required by EU AI Act Articles 13 and 50. ```python theme={null} card = client.get_transparency_card("agt_abc123") ``` Agent ID **Returns**: ```json theme={null} { "agent_id": "agt_abc123", "agent_name": "production-summarizer", "purpose": "Summarizes customer support tickets for the support team", "framework": "crewai", "model_provider": "openai", "model_name": "gpt-4o", "risk_level": "limited", "capabilities": [ "Text summarization", "Ticket categorization" ], "limitations": [ "May miss context in multi-language tickets", "Does not handle image attachments" ], "human_oversight": "Output reviewed by support team leads before customer communication", "data_sources": "Customer support ticket text (no PII stored)", "generated_at": "2026-03-17T10:00:00Z" } ``` ## create\_incident() Report a serious incident per EU AI Act Article 73. ```python theme={null} incident = client.create_incident( agent_id="agt_abc123", title="Discriminatory output in hiring agent", severity="high", description="The HR screening agent systematically ranked female candidates lower...", impact="Approximately 120 job applicants may have been affected.", immediate_actions="Agent suspended immediately.", root_cause="Training data contained historical hiring bias.", affected_persons_count=120, involves_health_or_death=False, ) ``` Agent ID Short title describing the incident `serious` or `critical` (critical if death or serious health damage) Detailed description of what happened Description of the impact Actions taken immediately after discovery Root cause analysis (can be updated later) Estimated number of affected persons If `true`, the reporting deadline is 2 days instead of 15 See [Incident Reporting](/governance/incidents) for the full workflow including authority notification. ## list\_incidents() List incident reports, optionally filtered by status. ```python theme={null} incidents = client.list_incidents(status="open", limit=20) ``` ## update\_incident() Update an incident's status, root cause, corrective actions, or authority-notified flag. ```python theme={null} client.update_incident(42, status="resolved", root_cause="Training data bias corrected") ``` # Cost Intelligence Source: https://docs.meshai.dev/sdk-reference/cost Query token spend by agent, team, and model ## get\_cost\_summary() Get an aggregate cost summary for your tenant over a time period. ```python theme={null} summary = client.get_cost_summary( start="2026-03-01", end="2026-03-17", ) ``` Start date (ISO 8601). Defaults to start of current month. End date (ISO 8601). Defaults to today. **Returns**: ```json theme={null} { "total_cost_usd": 1245.67, "total_input_tokens": 15234000, "total_output_tokens": 4567000, "total_requests": 8923, "start": "2026-03-01T00:00:00Z", "end": "2026-03-17T23:59:59Z" } ``` ## get\_cost\_by\_agent() Break down costs by individual agent. ```python theme={null} by_agent = client.get_cost_by_agent( start="2026-03-01", end="2026-03-17", ) ``` Start date (ISO 8601) End date (ISO 8601) **Returns**: ```json theme={null} [ { "agent_id": "agt_abc123", "agent_name": "production-summarizer", "team": "support-team", "total_cost_usd": 456.78, "input_tokens": 5600000, "output_tokens": 1200000, "requests": 3400 }, { "agent_id": "agt_def456", "agent_name": "lead-qualifier", "team": "sales-team", "total_cost_usd": 312.45, "input_tokens": 4100000, "output_tokens": 980000, "requests": 2100 } ] ``` ## get\_cost\_by\_model() Break down costs by model. ```python theme={null} by_model = client.get_cost_by_model( start="2026-03-01", end="2026-03-17", ) ``` Start date (ISO 8601) End date (ISO 8601) **Returns**: ```json theme={null} [ { "model_provider": "openai", "model_name": "gpt-4o", "total_cost_usd": 890.12, "input_tokens": 10200000, "output_tokens": 3100000, "requests": 5800 }, { "model_provider": "anthropic", "model_name": "claude-sonnet-4-20250514", "total_cost_usd": 355.55, "input_tokens": 5034000, "output_tokens": 1467000, "requests": 3123 } ] ``` # Governance Source: https://docs.meshai.dev/sdk-reference/governance Risk classification, policies, approvals, and audit trail via the SDK ## classify\_risk() Assign an EU AI Act risk level to an agent. ```python theme={null} classification = client.classify_risk( agent_id="agt_abc123", risk_level="high", justification="Processes employee performance data for HR decisions", assessed_by="compliance-team", ) ``` Agent ID Risk level: `minimal`, `limited`, `high`, `unacceptable` Reason for the classification Identifier of the person or system performing the assessment Optional list of domain tags associated with the classification Optional list of EU AI Act categories associated with the classification See [Risk Classification](/governance/risk-classification) for details on each level. ## create\_policy() Create a governance policy. ```python theme={null} policy = client.create_policy( name="production-model-allowlist", policy_type="model_allowlist", rules={"allowed_models": ["gpt-4o", "claude-sonnet-4-20250514"]}, conditions={"environments": ["production"]}, enabled=True, ) ``` Policy name One of: `model_allowlist`, `block_provider`, `require_approval`, `budget_limit`, `rate_limit`, `require_human_review`, `prompt_injection`, `pii_filter` Policy rules (varies by type; must be non-empty) Optional scoping: `agent_ids`, `team_ids`, `environments`, `risk_levels` Evaluation priority, 1 to 1000 Whether the policy is active See [Policies](/governance/policies) for all policy types, rules keys, and the enforcement model. ## list\_approvals() List HITL approval items. ```python theme={null} # All pending approvals pending = client.list_approvals(status="pending") # All approvals for an agent agent_approvals = client.list_approvals(agent_id="agt_abc123") ``` Filter by status: `pending`, `approved`, `denied`, `expired` Filter by agent ID Results per page See [HITL Approvals](/governance/approvals) for the full workflow. ## decide\_approval() Approve or deny a pending approval item. ```python theme={null} # Approve client.decide_approval( 12345, decision="approved", reviewer_id="reviewer-jane", reason="Agent configuration verified", ) # Deny client.decide_approval( 12345, decision="denied", reviewer_id="reviewer-jane", reason="Agent not authorized for production", ) ``` Approval request ID `approved` or `denied` Identifier of the reviewer making the decision Reason for the decision (recorded in audit trail) ## Additional Methods One-line reference for other governance methods. | Method | Description | | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | `get_risk_classification(agent_id)` | Get current risk classification for an agent. | | `get_risk_suggestion(agent_id)` | Get AI-assisted risk level suggestion based on agent metadata. | | `list_risk_classifications(**params)` | List all risk classifications. Supports risk\_level, page, limit. | | `get_policy(policy_id)` | Get a single policy. | | `update_policy(policy_id, **fields)` | Update policy fields such as name, enabled, priority, conditions, and rules. | | `delete_policy(policy_id)` | Delete a governance policy. | | `list_policies(**params)` | List governance policies. Supports policy\_type, enabled, page, limit. | | `evaluate_policies(agent_id, provider, model, team_id=None, environment="production")` | Dry-run evaluate all policies against a request context. | | `get_pending_count()` | Get count of pending approval requests. | ## list\_audit\_events() Query the immutable audit trail. ```python theme={null} # Recent events events = client.list_audit_events(limit=50) # Filtered events = client.list_audit_events( event_type="policy.violated", target_id="agt_abc123", from_date="2026-03-01T00:00:00Z", to_date="2026-03-17T23:59:59Z", limit=100, ) ``` Filter by event type (e.g., `agent.registered`, `policy.violated`) Filter by target entity ID Start of time range (ISO 8601) End of time range (ISO 8601) Results per page See [Audit Trail](/governance/audit-trail) for all event types and export options. # Installation Source: https://docs.meshai.dev/sdk-reference/installation Install the MeshAI Python SDK and configure optional dependencies ## Install ```bash theme={null} pip install meshai-sdk ``` The current release is `0.6.0`. Upgrade an existing environment with: ```bash theme={null} pip install --upgrade "meshai-sdk==0.6.0" ``` On Ubuntu/Debian, if you get `externally-managed-environment` error, create a virtual environment first: ```bash theme={null} python3 -m venv .venv && source .venv/bin/activate pip install meshai-sdk ``` ## Optional Dependencies Install extras for framework auto-tracking: ```bash theme={null} # OpenAI integration pip install meshai-sdk[openai] # Anthropic integration pip install meshai-sdk[anthropic] # CrewAI integration pip install meshai-sdk[crewai] # LangChain integration pip install meshai-sdk[langchain] # AutoGen integration pip install meshai-sdk[autogen] # Multiple integrations at once pip install "meshai-sdk[openai,anthropic,langchain]" ``` Additional integration extras are also available: `agno`, `bedrock`, `gemini`, `llamaindex`, `pydantic-ai`, and `semantic-kernel`. See the [Agno](/framework-guides/agno), [Bedrock](/framework-guides/bedrock), [Gemini](/framework-guides/gemini), [LlamaIndex](/framework-guides/llamaindex), [Pydantic AI](/framework-guides/pydantic-ai), and [Semantic Kernel](/framework-guides/semantic-kernel) guides for setup details. Install the `tracer` extra for OpenTelemetry sessions, spans, and the optional GenAI input-emission API introduced in `0.6.0`: ```bash theme={null} pip install "meshai-sdk[tracer]==0.6.0" ``` ## Recent releases | Version | Upgrade impact | | ------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `0.6.0` | Adds default-off GenAI input emission with local redaction. Tenant payload capture must also be enabled. | | `0.5.1` | Raises the `tracer` extra's OpenTelemetry minimum to `1.44.0`; no runtime behavior change. | | `0.5.0` | Sends default production OTLP traffic to `https://ingest.meshai.dev`; API, registry, cost, and heartbeat traffic continue using `base_url`. | For `0.5.0`, an explicitly self-hosted or localhost `base_url` keeps telemetry on that deployment. Set `ingest_url` when you need a separate collector endpoint. This routing behavior continues in `0.6.0`. ## Requirements * Python 3.10+ * An API key from [app.meshai.dev](https://app.meshai.dev) ## Configuration The SDK can be configured via constructor arguments, environment variables, or a combination of both. ### Environment Variables | Variable | Description | Required | | --------------------------- | -------------------------------------------------- | -------------------------------------- | | `MESHAI_API_KEY` | Your API key (`msh_...`) | Yes (if not passed to constructor) | | `MESHAI_BASE_URL` | API base URL | No (default: `https://api.meshai.dev`) | | `MESHAI_AGENT_NAME` | Default agent name | No | | `MESHAI_ENVIRONMENT` | Agent environment (`production`, `staging`, `dev`) | No (default: `production`) | | `MESHAI_HEARTBEAT_INTERVAL` | Heartbeat interval in seconds | No (default: `30`) | | `MESHAI_TIMEOUT` | HTTP request timeout in seconds | No (default: `10`) | ### Constructor vs Environment Constructor arguments take precedence over environment variables: ```python theme={null} from meshai import MeshAI # Uses MESHAI_API_KEY from env client = MeshAI(agent_name="my-agent") # Explicit key overrides env client = MeshAI(api_key="msh_...", agent_name="my-agent") ``` ## Verify Installation ```python theme={null} from meshai import MeshAI client = MeshAI(api_key="msh_...", agent_name="test-agent") agent = client.register(framework="custom", model_provider="openai") print(f"Registered: {agent['id']}") ``` ## Next Steps All constructor parameters and configuration options Auto-tracking for OpenAI, Anthropic, CrewAI, LangChain, AutoGen # Security Source: https://docs.meshai.dev/sdk-reference/security Kill switch, quarantine, agent lifecycle, ownership, relationships, and security posture via the SDK ## block\_agent() Block an agent from making requests (kill switch). ```python theme={null} client.block_agent("agt_abc123", reason="Suspected credential leak") ``` ## unblock\_agent() Remove a block from an agent. ```python theme={null} client.unblock_agent("agt_abc123") ``` ## quarantine\_agent() Quarantine a shadow or suspicious agent. ```python theme={null} client.quarantine_agent("agt_abc123", reason="Unregistered agent detected on production traffic") ``` ## release\_quarantine() Release an agent from quarantine. ```python theme={null} client.release_quarantine("agt_abc123") ``` ## list\_quarantined\_agents() List all quarantined agents. ```python theme={null} quarantined = client.list_quarantined_agents() ``` ## list\_expired\_agents() List agents past their expiry date. ```python theme={null} expired = client.list_expired_agents() ``` ## list\_agents\_due\_review() List agents due for access review. ```python theme={null} due_review = client.list_agents_due_review() ``` ## set\_agent\_lifecycle() Configure an agent's expiry date, review frequency, and sponsor. ```python theme={null} client.set_agent_lifecycle( "agt_abc123", expires_at="2026-12-31T00:00:00Z", review_frequency="quarterly", sponsor_id="user_42", ) ``` ## assign\_owner() Assign an owner to an agent, with an optional permission set. ```python theme={null} client.assign_owner( "agt_abc123", owner_type="team", owner_id="support-team", owner_name="Support Team", permissions={"can_edit": True, "can_delete": False}, ) ``` ## list\_agent\_owners() List all owners of an agent. ```python theme={null} owners = client.list_agent_owners("agt_abc123") ``` ## remove\_owner() Remove an owner from an agent. ```python theme={null} client.remove_owner("agt_abc123", 7) ``` ## list\_owner\_agents() List all agents owned by a specific owner. ```python theme={null} agents = client.list_owner_agents("support-team") ``` ## get\_agent\_relationships() Get an agent's model, provider, and tool dependencies. ```python theme={null} relationships = client.get_agent_relationships("agt_abc123") ``` ## get\_relationship\_graph() Get the full agent relationship graph as nodes and edges. ```python theme={null} graph = client.get_relationship_graph() ``` ## get\_security\_posture() Get the tenant's security posture score (0-100) across six dimensions. ```python theme={null} posture = client.get_security_posture() ``` # Telemetry Source: https://docs.meshai.dev/sdk-reference/telemetry Heartbeats, usage tracking, and auto-tracking wrappers ## heartbeat() Send a single heartbeat to confirm the agent is alive. Called automatically by `start_heartbeat()`, but you can also call it manually. ```python theme={null} client.heartbeat() ``` The heartbeat updates the agent's `last_heartbeat` timestamp and keeps its status as `healthy`. If no heartbeat is received for 2 minutes, the agent status changes to `degraded`. After 5 minutes, it changes to `down`. ## start\_heartbeat() Start a background thread that sends heartbeats at a regular interval. ```python theme={null} client.start_heartbeat() ``` The interval is configured via the `heartbeat_interval` constructor parameter (default: 30 seconds). The background thread is a daemon thread that stops automatically when your process exits. ```python theme={null} # Custom interval client = MeshAI(api_key="msh_...", agent_name="my-agent", heartbeat_interval=60) client.register(framework="custom", model_provider="openai") client.start_heartbeat() # Sends every 60 seconds ``` ## stop\_heartbeat() Stop the background heartbeat thread started by `start_heartbeat()`. ```python theme={null} client.stop_heartbeat() ``` ## track\_usage() Report a single LLM usage event: tokens consumed, model used, and optional cost. ```python theme={null} client.track_usage( model_provider="openai", model_name="gpt-4o", input_tokens=1500, output_tokens=800, request_type="chat.completions", cost_usd=0.035, ) ``` LLM provider: `openai`, `anthropic`, `google`, `nvidia`, `bedrock` Model identifier (e.g., `gpt-4o`, `claude-sonnet-4-20250514`) Number of input/prompt tokens Number of output/completion tokens Type of request (e.g., `chat.completions`, `embeddings`) Explicit cost in USD. If omitted, MeshAI calculates cost based on model pricing tables. ## Auto-Tracking Wrappers Instead of calling `track_usage()` manually, use framework wrappers that capture usage automatically: ```python theme={null} # OpenAI from meshai.integrations.openai import wrap_openai oai = wrap_openai(openai.OpenAI(), meshai=client) # Anthropic from meshai.integrations.anthropic import wrap_anthropic ant = wrap_anthropic(anthropic.Anthropic(), meshai=client) # CrewAI from meshai.integrations.crewai import MeshAICrewCallback crew = Crew(callbacks=[MeshAICrewCallback(meshai=client)]) # LangChain from meshai.integrations.langchain import MeshAILangChainCallback chain.invoke(input, config={"callbacks": [MeshAILangChainCallback(meshai=client)]}) # AutoGen from meshai.integrations.autogen import MeshAIAutoGenCallback agent = AssistantAgent(callbacks=[MeshAIAutoGenCallback(meshai=client)]) ``` See the [Framework Guides](/framework-guides/openai) for complete examples. ## Optional GenAI input emission SDK `0.6.0` can emit the input attributes supported by MeshAI's sanitized payload-capture pipeline. Input emission is disabled by default and requires both local SDK opt-in and a separately enabled tenant payload-capture setting. ```python theme={null} from meshai.tracer import Tracer tracer = Tracer( api_key="msh_...", service_name="case-summarizer", capture_inputs=True, ) with tracer.session() as session: session.record_llm_call( "anthropic", "claude-sonnet-4-6", input_tokens=120, output_tokens=40, input_messages=[{"role": "user", "content": "Summarize this case"}], system_instructions=[{"type": "text", "content": "Be concise"}], retrieval_query="customer case history", ) ``` The SDK emits only `gen_ai.input.messages`, `gen_ai.system_instructions`, and `gen_ai.retrieval.query.text`. It applies local known-secret redaction, and the server sanitizes again before storage. Sanitized input is not anonymous or guaranteed to be free of personal data. Without both opt-ins, MeshAI receives structural telemetry only. See [Sanitized Input Capture](/governance/payload-capture) for retention, failure, and legal-basis boundaries. ## shutdown() Flush all pending heartbeat and usage events, stop the background heartbeat, and close the HTTP transport. Called automatically on process exit via `atexit`, but you can call it manually to flush and close early. ```python theme={null} client.shutdown() ```