Sign In

@beyondnet/evolith-mcp

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@beyondnet/evolith-mcp

Evolith MCP Gateway — NestJS-based Model Context Protocol server for AI agents. Supports stdio and SSE transports.

latest
Source
npmnpm
Version
1.3.3
Version published
Weekly downloads
323
1192%
Maintainers
1
Weekly downloads
 
Created
Source

@beyondnet/evolith-mcp

Evolith MCP Gateway — First-Class Model Context Protocol Server

Bilingual navigation: Versión en Español

Decouples the MCP server from the CLI. It is a first-class product that exposes the MCP tools as a Gateway talking to @beyondnet/evolith-core (the reusable business-logic layer), instead of shelling out to CLI subprocesses.

Table of contents

Architecture diagram

sequenceDiagram
    participant Agent as "AI Agent<br/>(Cursor, Claude Desktop, Custom)"
    participant Gateway as "MCP Gateway<br/>@beyondnet/evolith-mcp"
    participant Core as "Business Logic<br/>@beyondnet/evolith-core"
    participant FS as "File System"
    participant Git as "Git"

    Note over Agent,Gateway: Transport: stdio (local) or Streamable HTTP (remote)

    Agent->>+Gateway: tools/call { name: "evolith-validate", args: { path: "/repo" } }

    Gateway->>Gateway: 1. Generate correlationId (evl-xxx)
    Gateway->>Gateway: 2. Lookup tool in ToolRegistry
    Gateway->>Gateway: 3. ABAC authorization check
    Gateway->>Gateway: 4. Start timing + structured log (Pino)

    Gateway->>+Core: ValidateSatelliteUseCase.execute({ satellitePath })
    Core->>+FS: Read evolith.yaml, rulesets/
    FS-->>-Core: Configuration + rule definitions

    Core->>+Git: Check ADR history, phase state
    Git-->>-Core: Phase & commit data

    Core->>Core: Evaluate rules (Native + OPA)
    Core-->>-Gateway: ValidationResult { status, issues }

    Gateway->>Gateway: 5. Wrap in SuccessEnvelope { success, data, meta }
    Gateway->>Gateway: 6. Audit log + completion duration

    Gateway-->>-Agent: { content: [{ type: "text", text: "{...}" }] }

    Note over Agent,Gateway: All errors wrapped in ErrorEnvelope with EvolithErrorCode

Transports

TransportUseCommand
stdio (JSON-RPC 2.0)Local agents, Cursor, Claude Desktopevolith-mcp serve
Streamable HTTP (official MCP SDK)Remote agents, scalabilityevolith-mcp serve --transport http --port 49100

The default port is 3000 (main.ts: env PORT or --port, falling back to 3000). The 49100 used in the examples is an arbitrary value, not the default.

Logs are always written to stderr (Pino), because stdout is reserved for the JSON-RPC stream of the stdio transport.

Installation and configuration

Installation

# From the monorepo
npm install @beyondnet/evolith-mcp

# Or globally
npm install -g @beyondnet/evolith-mcp

Usage

# stdio (default) — for Cursor, Claude Desktop, etc.
evolith-mcp serve

# HTTP — for remote integration
evolith-mcp serve --transport http --port 49100

Environment variables

VariableDefaultDescription
TRANSPORTstdioActive transport: stdio or http
PORT3000Port for the HTTP transport
MCP_HTTP_HOST0.0.0.0Bind host of the HTTP server. Use 127.0.0.1 for local-only
EVOLITH_API_KEYAPI key for authentication on the HTTP transport
EVOLITH_MCP_ALLOW_NO_AUTHfalseHTTP only. Allows HTTP to start without an API key (non-production only). Ignored in production and on stdio (which warns at startup)
JWT_SECRETOptional secret used to validate a Bearer JWT (HS256) in addition to the API key
NODE_ENVdevelopmentIn production, HTTP auth is mandatory
LOG_LEVELinfoPino log level: trace, debug, info, warn, error
REDIS_URLRedis URL for the resource cache (e.g. redis://localhost:6379). The cache is optional.
OTEL_EXPORTER_OTLP_ENDPOINTOpenTelemetry endpoint for tracing
OTEL_SERVICE_NAMEevolith-mcpService name used in the traces
EVOLITH_MCP_REQUEST_STATE_SECRETKey that seals the MRTR requestState (2026-07-28 path). Falls back to EVOLITH_API_KEY, then JWT_SECRET, then a per-process key. Set it explicitly whenever more than one replica is served, or an approval retry landing on another replica is rejected
EVOLITH_MCP_RESOURCE_AUTH_SERVERSComma-separated authorization server issuers published in the Protected Resource Metadata document. Defaults to EVOLITH_MCP_OAUTH_ISSUER
EVOLITH_MCP_RESOURCE_URIrequest hostCanonical URI of this server (RFC 8707 resource identifier) published as resource
EVOLITH_MCP_RESOURCE_SCOPESread writeScopes published as scopes_supported and challenged in WWW-Authenticate

The binary also accepts the flags --transport/-t, --port/-p, --api-key and --allow-no-auth (HTTP only), as well as the evolith-mcp version subcommand.

Authentication

stdio transport

No request authentication is required: the process is local, single-user, and the agent runs it directly. The transport establishes an explicit local session principal (id=local-stdio-session, role=local-session, roles=[local-session, operator], scopes=[read, write]) that is recorded in the audit trail of every call (GT-572).

This is not an authorization bypass: ABAC (native + OPA) is still evaluated on every tools/call with that identity, the deploy tools are still denied in production (they require architect), and every mutative tool still demands the HITL gate { apply, approvalToken }. --allow-no-auth / EVOLITH_MCP_ALLOW_NO_AUTH do not apply to stdio (there is no request authentication to skip); if they are passed together with --transport stdio, the server warns about it on stderr at startup.

HTTP transport

In production (NODE_ENV=production), authentication is mandatory: validateAuth() ignores EVOLITH_MCP_ALLOW_NO_AUTH and rejects every request without a valid credential (401). The value of EVOLITH_API_KEY is an arbitrary secret (any string; no prefix required) compared by equality. It is accepted in either of these two headers:

Authorization: Bearer <EVOLITH_API_KEY>
x-api-key: <EVOLITH_API_KEY>

/health is public (a liveness probe) and requires no credential.

When an OAuth issuer is configured, /.well-known/oauth-protected-resource (and the path-inserted /.well-known/oauth-protected-resource/<path>) is also public: it is the RFC 9728 document an unauthenticated client reads to discover which authorization server to go to, so gating it behind the credential it is trying to obtain would make discovery impossible. It carries no MCP data — only the issuer, the resource identifier and the scope names. A 401 from a protected resource additionally carries a WWW-Authenticate: Bearer resource_metadata="…", scope="…" challenge, which is the discovery mechanism MCP clients must prefer. Without an issuer the endpoint returns 404 rather than publishing a document with an empty authorization_servers.

Client registration never flows through this server: it is a resource server, and the 2026-07-28 revision has clients obtain a client_id from a Client ID Metadata Document (or pre-registration) at the authorization server. Dynamic Client Registration is deprecated and is not implemented here; protected-resource-metadata.spec.ts fails the build if a registration endpoint is ever introduced.

Protocol revisions

The server answers two protocol revisions on the same HTTP endpoint:

RevisionHow a request selects itShape
2026-07-28 (current)_meta["io.modelcontextprotocol/protocolVersion"] on every request, or a server/discover callStateless. No initialize, no notifications/initialized, no Mcp-Session-Id. Every result carries resultType; the approval gate is expressed as an InputRequiredResult with a sealed requestState (MRTR)
2025-11-25an initialize requestThe handshake-based path served by @modelcontextprotocol/sdk, which mints and requires Mcp-Session-Id

Both revisions run through one dispatch, so ABAC (native + OPA), the scope gate, the approval gate and the audit trail are the same code on either path. The 2025-11-25 path is retained because the published SDK still declares it as its latest revision; it is not an alternative design.

On the 2026-07-28 path a state-changing tool answers resultType: "input_required" with an elicitation/create request and an opaque requestState. The client gathers the human's approval and retries the original call — new JSON-RPC id, same parameters, plus requestState and inputResponses. The requestState is sealed with AES-256-GCM and bound to the principal, the tenant, the originating call and a short TTL, so it cannot be replayed across users, calls or time. A caller that already holds an approval may still pass { apply: true, approvalToken } inline and skip the round trip, exactly as on the 2025-11-25 path.

The ApiKeyProvisioningService (below) is an advanced and optional mechanism for issuing keys with an evk_ prefix, a SHA-256 hash and a TTL. It is independent of the startup EVOLITH_API_KEY described here.

API key provisioning

The ApiKeyProvisioningService manages the lifecycle of the keys:

OperationDescription
generateKey(label, options)Generates a key with an evk_ prefix, a SHA-256 hash and a configurable TTL (90 days by default)
validateKey(rawKey)Validates the key against the stored hash and checks expiry
rotateKey(keyId)Revokes the current key and generates a new one for the same client
revokeKey(keyId)Revokes a key immediately

Keys carry scopes: read, write, admin. They are bound to a tenant.

ABAC model

The AbacEvaluator controls which tools each user may invoke, based on their roles:

Tool typeAllowed rolesEnvironment
Read (list, get, status)Every authenticated roleAny
Write (fix, install, set)operator, sre, architect, adminAny
Writedeveloper, qaNon-production only
Deploy (deploy, publish, merge)architect, admin, operator, sreAny
DeployAnyone except architectBlocked in production

ABAC codes:

CodeCause
ABAC-01Tool denied for the user's role/environment
ABAC-02User with no roles — every tool is denied
ABAC-03Tool not classified into any known group

Tool classification (substring heuristic). The internal role sets are DEVELOPER = {developer, qa}, OPERATOR = {operator, sre} and ARCHITECT = {architect, admin}. The read/write/deploy classification of each tool is a heuristic over its name (abac-evaluator.ts): it counts as read if the name contains read/list/get (or does not begin with evolith-); as write if it contains write/replace/run/fix/advance; as deploy if it contains deploy/publish/merge. Because of that heuristic, evolith-phase-advance is classified as write (the advance substring), even though it only proposes the transition. A tool that fits no group is rejected with ABAC-03.

Authentication precedence (HTTP). The guard (mcp-server-auth.ts) evaluates the API key first: if the Authorization: Bearer <token> or the x-api-key header matches EVOLITH_API_KEY, it grants an admin context (role admin, every tool allowed). Only if the key does not match and JWT_SECRET is defined does it try to validate the Bearer as a JWT HS256; in that case the roles in the JWT payload are what feed ABAC. /health is public. In production, auth is mandatory (it ignores EVOLITH_MCP_ALLOW_NO_AUTH).

Available tools (47)

The tools are obtained at runtime via tools/list. All of them return raw data, which the Gateway wraps in a SuccessEnvelope or an ErrorEnvelope.

Validation

ToolDescriptionMutative
evolith-validateValidates a repository against the Evolith governance rules (GOV, INH, ACL, OCB)No
evolith-composable-validateCombinable multi-mode validation: SDLC, Architecture, Ruleset, ADR, Ad-hocNo

evolith-composable-validate schema:

{
  "path": "string (required) — path to the satellite repository",
  "corePath": "string — path to the Evolith Core",
  "engine": "'native' | 'opa' — evaluation engine (default: native)",
  "topology": "'modular-monolith' | 'microservices' | 'serverless' | ... — enables Architecture mode",
  "phase": "'discovery' | 'design' | 'construction' | 'qa' | 'release' — enables SDLC mode (the schema also accepts the legacy aliases 'f1'..'f5', deprecated)",
  "ruleset": "string — enables Ruleset mode",
  "adr": "'adr-0002' | 'adr-0005' | 'adr-0010' | ... — enables ADR mode",
  "file": "string — enables Ad-hoc mode over a single file"
}

Modes are enabled by combining fields. Several of them can be used in a single call.

Architecture

ToolDescriptionMutative
evolith-architecture-validateValidates a satellite project against the architecture rulesNo
evolith-drift-detectDetects drift between the declared architecture and the real oneNo

Topologies

ToolDescriptionMutative
evolith-topology-listLists every architecture topology available in Evolith CoreNo
evolith-topology-getGets the full manifest of a topology by IDNo

evolith-topology-list schema:

{
  "corePath": "string — path to the Core (optional, default: ../evolith)"
}

evolith-topology-get schema:

{
  "id": "string (required) — topology ID (e.g. modular-monolith)",
  "corePath": "string — path to the Core (optional)"
}

Available topologies: modular-monolith, distributed-modules, microservices, serverless, edge-computing, event-driven, data-mesh, agentic-ai

SDLC gates

ToolDescriptionMutative
evolith-gate-evaluateEvaluates a specific SDLC phase gateNo
evolith-phase-advanceProposes a phase transitionNo¹

¹ evolith-phase-advance only proposes the transition — it does not execute it. Executing it is the responsibility of the operator or of the Tracker.

SDLC

ToolDescriptionMutative
evolith-sdlc-statusGets the current SDLC phase state of the repositoryNo
evolith-sdlc-handoffRuns the phase handoff, generating the evidence manifestYes
evolith-dora-metricsApproximates DORA metrics from the Git history: deployment frequency, lead time (approx.), total and merge commits within the window (days, default 90)No

MoSCoW

ToolDescriptionMutative
evolith-moscow-createCreates a MoSCoW matrix for a phase of the projectNo²
evolith-moscow-loadLoads an existing MoSCoW matrixNo
evolith-moscow-updateUpdates items in the MoSCoW matrixNo²
evolith-moscow-removeRemoves items from the matrixNo²
evolith-moscow-listLists the MoSCoW matrices of the projectNo
evolith-moscow-validateValidates that the matrix is well formedNo
evolith-moscow-reportGenerates a MoSCoW prioritization reportNo

² The MoSCoW tools write to .evolith/moscow/{phase}.json but do not declare mutative: true in the code (moscow.tools.ts), so the dispatcher does not demand apply/approvalToken. Treat them as write operations that are not protected by the mutative guard.

Agents

ToolDescriptionMutative
evolith-agent-installInstalls an Evolith agent in the repositoryYes
evolith-agent-listLists the installed agentsNo
evolith-agent-validateValidates the configuration of an agentNo
evolith-agent-upgradeUpgrades an agent to the latest version of the templateYes
evolith-agent-removeRemoves an agent from the repositoryYes

Remediation

ToolDescriptionMutative
evolith-auto-fixApplies automatic fixes to the detected violationsYes

Configuration

ToolDescriptionMutative
evolith-config-getGets configuration values from evolith.yamlNo
evolith-config-setUpdates values in evolith.yamlYes

Observability

ToolDescriptionMutative
evolith-metricsReturns internal MCP Gateway metrics (calls, latency, errors)No

Available resources (9 + dynamic)

Resources are obtained via resources/list and read via resources/read.

Static resources (resources/list)

URINameDescription
evolith://rulesetsRulesetsLists every ruleset of Evolith Core
evolith://phase-gatesPhase GatesDefinitions and requirements of the phase gates
evolith://agentsAgentsList of installed Evolith agents
evolith://core/infoCore InfoGeneral Core information (version, total rulesets, capabilities)
evolith://governance/versionGovernance VersionVersion of the governance schema
evolith://core/versionCore VersionVersion of the Core schema
evolith://repository/configRepository ConfigContents of the current repository's evolith.yaml
evolith://moscow/phase-0MoSCoW Phase 0MoSCoW matrix for the discovery phase
evolith://architecture/topologiesArchitecture TopologiesList of every available topology

Dynamic URIs (reachable via resources/read)

URI PatternDescription
evolith://ruleset/{name}Contents of a ruleset by name (e.g. evolith://ruleset/governance/base)
evolith://agent/{name}Definition of an installed agent (e.g. evolith://agent/winston)
evolith://architecture/topology/{id}Manifest of a topology (e.g. evolith://architecture/topology/modular-monolith)
evolith://open-core/artifactsOpen-Core boundary (OCB) rules
evolith://acl/rulesAnti-Corruption Layer rules
evolith://moscow/{phase}MoSCoW analysis of any phase (e.g. evolith://moscow/phase-1)

Available prompts (8)

Prompts are obtained via prompts/list and invoked via prompts/get.

PromptDescriptionArguments
evolith/validate-repositoryValidate a repository against the governance rulespath (req), ruleset (opt)
evolith/agent-onboardingInstall and configure a new agentname (req), template (opt: standard/minimal/enterprise)
evolith/architecture-reviewF1/F2/F3 architecture reviewpath (req), level (opt: F1/F2/F3)
evolith/prepare-discoveryPrepare the artifacts of the discovery phasepath (req)
evolith/phase-gate-checkCheck phase gate readinesspath (req)
evolith/sdlc-handoffRun the SDLC phase handoffpath (req), fromPhase (req), toPhase (req)
evolith/ruleset-analysisAnalyse compliance with a rulesetruleset (req), path (opt)
evolith/moscow-prioritizationCreate a MoSCoW matrix for the SDLCpath (req), phase (opt, default: phase-0)

Mutative operations

Tools marked as mutative (mutative: true) require explicit approval in order to prevent accidental changes. The dispatcher (mcp-tool-dispatch.ts:137) rejects the call with FORBIDDEN unless the request carries both fields:

{
  "name": "winston",
  "dir": "/path/to/repo",
  "apply": true,
  "approvalToken": "<non-empty-token>"
}
  • apply must be exactly true.
  • approvalToken must be a non-empty string. The server never logs it in the clear: it reduces it to a sha256:… fingerprint before auditing it.

The approvalToken is the approval contract at the protocol level. Some tool schemas still declare a confirm field, and the helper isMutationAllowed() exists (it reads mcp.allowMutations from evolith.yaml), but the guard that actually blocks execution in handleCallTool is apply + approvalToken — neither confirm nor mcp.allowMutations replaces it.

Mutative tools

ToolOperation
evolith-agent-installWrites the agent files into the repository
evolith-agent-upgradeOverwrites the agent configuration
evolith-agent-removeDeletes the agent directory
evolith-config-setModifies evolith.yaml
evolith-sdlc-handoffGenerates the handoff manifest and writes state
evolith-auto-fixApplies automatic fixes to the code

Exactly 6 tools declare mutative: true in the code (config-set, sdlc-handoff, agent-install, agent-upgrade, agent-remove, auto-fix). The MoSCoW tools do write to disk but are not marked as mutative, so the apply/approvalToken guard does not apply to them.

Internal architecture

The Gateway is a NestJS application (modules + dependency injection).

@beyondnet/evolith-mcp/
├── src/
│   ├── main.ts                         ← Bootstrap, parseArgs, stdio/HTTP startup
│   ├── app.module.ts                   ← Root module
│   ├── common/
│   │   ├── errors.ts                   ← ErrorCodes + DomainException
│   │   ├── envelopes.ts                ← SuccessEnvelope / ErrorEnvelope + correlationId
│   │   └── stderr-logger.ts            ← LoggerService over Pino → stderr
│   ├── mcp/
│   │   ├── mcp.module.ts
│   │   ├── tool.interface.ts           ← McpTool interface + MCP_TOOLS token
│   │   ├── tool-registry.service.ts    ← dynamic tool registry
│   │   ├── mcp-server.service.ts       ← MCP SDK Server + dispatch + transports
│   │   ├── mcp-tool-dispatch.ts        ← dispatch with ABAC + audit + mutative guard
│   │   ├── mcp-server-auth.ts          ← HTTP authentication (EVOLITH_API_KEY)
│   │   ├── abac-evaluator.ts           ← native ABAC evaluator + OPA
│   │   ├── api-key-provisioning.service.ts  ← API key lifecycle
│   │   ├── audit-logger.ts             ← structured log of every tool call
│   │   ├── mcp-cache.service.ts        ← resource cache in Redis
│   │   ├── metrics.service.ts          ← internal Gateway metrics
│   │   ├── prompts.service.ts          ← serves prompts/list and prompts/get
│   │   └── resources.service.ts        ← serves resources/list and resources/read
│   ├── tools/
│   │   ├── tools.module.ts             ← registers every tool
│   │   ├── validate.tool.ts            ← evolith-validate
│   │   ├── composable-validate.tool.ts ← evolith-composable-validate (GT-312)
│   │   ├── architecture.tools.ts       ← evolith-architecture-validate, drift-detect
│   │   ├── topology.tools.ts           ← evolith-topology-list, topology-get
│   │   ├── gate.tools.ts               ← evolith-gate-evaluate
│   │   ├── phase-advance.tools.ts      ← evolith-phase-advance
│   │   ├── sdlc.tools.ts               ← sdlc-status, sdlc-handoff, dora-metrics
│   │   ├── moscow.tools.ts             ← moscow-create/load/update/remove/list/validate/report
│   │   ├── agent.tools.ts              ← agent-install/list/validate/upgrade/remove
│   │   ├── auto-fix.tools.ts           ← evolith-auto-fix
│   │   ├── config.tools.ts             ← config-get, config-set
│   │   └── metrics.tool.ts             ← evolith-metrics
│   ├── resources/
│   │   └── corpus-resource.handler.ts  ← handler for documentary corpus resources
│   ├── watcher/
│   │   └── watcher.service.ts          ← watches workspace files for changes
│   └── domain/
│       └── domain.module.ts            ← wires @beyondnet/evolith-core to @beyondnet/evolith-infra-providers

@beyondnet/evolith-core               ← business logic (use-cases, validators, types)
@beyondnet/evolith-infra-providers    ← adapters (NodeFileSystem, YamlConfigParser, DiskRulesetRepository)

WatcherService

WatcherService watches workspace files (e.g. evolith.yaml) in order to invalidate caches or trigger re-validations when the user edits the configuration while the Gateway is running. It is enabled automatically on the long-lived stdio transport.

CorpusResourceHandler

Handles access to documentary corpus resources (ADRs, playbooks, specs) so that agents can read structured architectural context without invoking mutative tools.

Agent use cases

1. Repository validation from Claude Desktop

// prompts/get
{
  "name": "evolith/validate-repository",
  "arguments": { "path": "/Users/me/my-service" }
}

The prompt guides the agent to use evolith-validate and to report the blocking violations.

2. Agent onboarding from Cursor

// prompts/get
{
  "name": "evolith/agent-onboarding",
  "arguments": { "name": "guardian", "template": "enterprise" }
}

The agent will invoke evolith-agent-install and evolith-agent-validate in sequence.

3. Automated architecture review

// tools/call
{
  "name": "evolith-composable-validate",
  "arguments": {
    "path": "/repo",
    "topology": "modular-monolith",
    "phase": "design",
    "engine": "native"
  }
}

Combines SDLC and Architecture validation in a single call.

4. A full SDLC cycle with MoSCoW + gate check

1. tools/call evolith-sdlc-status     → current state of the phase
2. tools/call evolith-moscow-create   → create the prioritization matrix
3. tools/call evolith-gate-evaluate   → evaluate the gate of the current phase
4. tools/call evolith-sdlc-handoff    → generate the handoff manifest
5. tools/call evolith-phase-advance   → propose moving on to the next phase

5. Querying the topologies before validating

// tools/call
{ "name": "evolith-topology-list" }
// → list of available topologies

{ "name": "evolith-topology-get", "arguments": { "id": "agentic-ai" } }
// → full manifest with rules and requirements

Client configuration

Cursor (~/.cursor/config.json)

{
  "mcpServers": {
    "evolith": {
      "command": "evolith-mcp",
      "args": ["serve"],
      "env": {
        "LOG_LEVEL": "info"
      }
    }
  }
}

Claude Desktop (claude_desktop_config.json)

{
  "mcpServers": {
    "evolith": {
      "command": "evolith-mcp",
      "args": ["serve"]
    }
  }
}

Custom agent (HTTP transport)

# Start the HTTP server
EVOLITH_API_KEY=evk_abc123 evolith-mcp serve --transport http --port 49100

# Call it from the agent
curl -X POST http://localhost:49100/mcp \
  -H "Authorization: Bearer evk_abc123" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"tools/call","params":{"name":"evolith-validate","arguments":{"path":"/repo"}},"id":1}'

SmartCLI integration

Migration plan away from evolith-cli mcp

Phase 1 — Coexistence (current): evolith-cli mcp keeps working. evolith-mcp serve is the new entry point.

Phase 2 — Deprecation: evolith-cli mcp will emit a console.warn. Migrate the Cursor / Claude Desktop configurations to evolith-mcp.

Phase 3 — Removal: Drop the MCP code from @beyondnet/evolith-cli in a major version bump. The CLI keeps its validation commands.

Behavioural differences

Aspectevolith-cli mcp (legacy)evolith-mcp (new)
Transportstdio onlystdio + Streamable HTTP
AuthNo authABAC + API keys over HTTP
CacheNo cacheOptional Redis
ObservabilityBasic logsPino + OTEL + audit logger
ToolsA subsetThe full 47 tools

Extension guide

To add a new tool:

  • Create src/tools/my-tool.tool.ts implementing McpTool (schema, execute; add readonly mutative = true if it changes state).
  • Inject whichever domain service it needs (from @beyondnet/evolith-core).
  • Return raw data — McpServerService wraps it automatically in a SuccessEnvelope and captures errors into an ErrorEnvelope.
  • Register the tool in tools.module.ts: add the provider and include it in the MCP_TOOLS factory.
import { Injectable } from "@nestjs/common";
import { McpTool, McpToolSchema } from "../mcp/tool.interface";

@Injectable()
export class MyTool implements McpTool {
  readonly schema: McpToolSchema = {
    name: "evolith-my-tool",
    description: "Description of what it does",
    inputSchema: {
      type: "object",
      properties: { param1: { type: "string", description: "..." } },
      required: ["param1"],
    },
  };

  async execute(args: Record<string, unknown>): Promise<unknown> {
    if (!args.param1) throw new Error("param1 is required");
    return { ok: true };
  }
}

For mutative tools, add readonly mutative = true. The dispatcher will then demand { "apply": true, "approvalToken": "..." } in the request before it runs the tool.

Observability

Pino logs → stderr

Every log goes to stderr (never stdout). Structured JSON format with correlationId, tool, duration and success.

# Follow the logs live (stdio)
evolith-mcp serve 2>&1 | grep '"level"'

evolith-metrics tool

Returns the internal metrics of the Gateway:

{
  "uptimeMs": 1820345,
  "totalCalls": 142,
  "totalFailures": 4,
  "tools": {
    "evolith-validate": { "calls": 80, "failures": 1, "totalLatencyMs": 1440, "avgLatencyMs": 18 },
    "evolith-gate-evaluate": { "calls": 32, "failures": 0, "totalLatencyMs": 992, "avgLatencyMs": 31 }
  },
  "recentErrors": ["RULESET_NOT_FOUND: ..."]
}

OpenTelemetry

OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 \
OTEL_SERVICE_NAME=evolith-mcp \
evolith-mcp serve

Audit Logger

Every tool call is recorded with: toolName, userId, tenant, environment, allowed (ABAC), durationMs and correlationId. The records go to stderr in JSON format.

Good practices

  • Use prompts as the entry point for agent workflows — they spare the agent from having to reason out the sequence of tools.
  • Do not confirm mutative calls in bulk without first validating with the equivalent read-only tools.
  • Run evolith-validate before evolith-auto-fix so you know the real scope of the changes.
  • On production HTTP, rotate the API keys every 90 days and restrict scopes to the minimum needed.
  • Redis is optional but recommended on long-lived installations, to avoid repeated filesystem reads in resources/read.
  • Use evolith-composable-validate instead of separate calls when several modes are needed — it cuts latency and correlates the results.

Troubleshooting

stdio: logs appear interleaved with the MCP response

Logs go to stderr. If the client merges stdout and stderr, separate the streams:

evolith-mcp serve 2>/tmp/mcp.log

stdio: Refusing to start the MCP stdio transport (GT-572)

Under NODE_ENV=production, the stdio transport does not receive the local-session principal implicitly: it demands the same configured credential as any other production surface. Without it the server does not start — it fails loudly at startup on stderr and exits with code 78 (EX_CONFIG), instead of advertising all of its tools and then denying every tools/call with FORBIDDEN.

Fixes (any one of them):

export EVOLITH_API_KEY=<key>                                  # container: -e EVOLITH_API_KEY=<key>
evolith-mcp serve --transport stdio --api-key <key>
NODE_ENV=development evolith-mcp serve --transport stdio      # local development session

--allow-no-auth / EVOLITH_MCP_ALLOW_NO_AUTH is an HTTP-only development switch and deliberately does not stand in for the production credential.

HTTP: 401 Unauthorized

Check that EVOLITH_API_KEY is configured on the server and that the request sends the same value in Authorization: Bearer <key> or x-api-key: <key>. The value is compared for exact equality (no evk_ prefix required). Under NODE_ENV=production, auth is mandatory even with EVOLITH_MCP_ALLOW_NO_AUTH=true.

Tool not found (Tool not found in registry)

The tool may not be registered in tools.module.ts. Check that the provider has been added and that the name in schema.name matches exactly the one being invoked.

ABAC-02: No roles present

The user context (mcp-user-context) carries no roles. On the HTTP transport, check that the JWT or the user context carries the role claims correctly.

Redis unavailable

The cache degrades gracefully. Resources are served straight from the filesystem with no cache, and a warning is emitted in the logs.

OPA: policy.wasm not found

The OPA evaluator requires sdk/cli/rulesets/opa/policy.wasm under CORE_PATH. The behaviour when a policy is missing is fail-closed (GT-348/349), not fail-open: if the file does not exist and NODE_ENV === "production", the evaluator returns allowed: false with the ABAC_POLICY_MISSING violation (a hard denial). Only in non-production environments does the OPA evaluator abstain, returning allowed: true so that the native policy decides. An error inside the OPA engine always denies. To force native evaluation, do not specify engine: "opa".

License

ISC — Beyondnet

Keywords

evolith

FAQs

Package last updated on 17 Aug 2026

Related posts