@iris-mcp/shared

v1.1.0

Published

Shared framework for the IRIS MCP servers: configuration, governance, audit and the IRIS gateway, plus the iris-mcp-credentials and iris-mcp-governance commands

Readme

@iris-mcp/shared

Internal shared library for the IRIS MCP Server Suite. This package provides the common HTTP client, configuration, error handling, and MCP server base class used by all five IRIS MCP server packages.

This is an internal dependency. It is not intended for direct installation or standalone use. Install one of the server packages instead: @iris-mcp/dev, @iris-mcp/admin, @iris-mcp/interop, @iris-mcp/ops, @iris-mcp/data

Part of the IRIS MCP Server Suite.


Public API

HTTP Client

  • IrisHttpClient -- HTTP client for communicating with IRIS. Handles Basic Auth, session cookie reuse, CSRF token management, and Atelier REST API envelope parsing. Supports GET, POST, PUT, DELETE, and HEAD methods.
  • IrisConnectionConfig (type) -- Configuration interface for IRIS connection: host, port, username, password, namespace, https flag.
  • RequestOptions (type) -- Options for HTTP requests: method, path, body, headers, query parameters, and an optional signal (Story 43.3). RequestOptions.signal is an AbortSignal: an already aborted signal sends no request and rejects with an IrisConnectionError of code CANCELLED, and an abort while the request is in flight aborts it and rejects with the same code. McpServerBase passes the signal of a call off the wire, so a call the client cancels (notifications/cancelled) aborts its IRIS requests.
  • AtelierEnvelope (type) -- Parsed Atelier REST API response envelope with status, result, and console output.
  • HeadResponse (type) -- Response type for HEAD requests: status code and headers.
  • loadConfig() -- Loads connection configuration from environment variables (IRIS_HOST, IRIS_PORT, etc.).

MCP Server Base

  • McpServerBase -- Abstract base class for all IRIS MCP servers. Handles tool registration, input validation (Zod), stdio transport setup, health checking, and auto-bootstrap of custom REST classes. It owns the tools/list, tools/call, prompts/get and resources/read handlers on top of the MCP SDK v2, and its protocol errors are SDK ProtocolErrors.
  • McpServerBaseOptions (type) -- Options for constructing an MCP server (name, version, tool definitions).
  • ToolDefinition (type) -- Tool definition interface including name, title, description, inputSchema (Zod), annotations, scope, and handler function.
  • ToolContext (type) -- Context passed to tool handlers: HTTP client, Atelier version, namespace resolver, paginator, and the optional confirm(request) (Story 43.3).
  • ToolContext.confirm(request) -- Asks the person to confirm a destructive change (AD-34). It is present only on a call off the wire and resolves to {proceed: true} or {proceed: false; result}. A gate calls it after every check of its own and right before its first IRIS write, and returns result unchanged when proceed is false. proceed is true for a client that does not declare form elicitation (today's contract) and after the person ticked Confirm and accepted; a decline, a dismissal and an accept without the tick resolve to a CONFIRMATION_DECLINED refusal that changes nothing. A context built directly (a unit test, an in-process callback) has no confirm, and a handler treats that as no question. A scope given as a function is resolved only when the client can be asked; when it throws, confirm rejects with that error and nothing is asked. ConfirmationRequest (operation, target, scope) and ConfirmationOutcome are exported as types. See the suite's Human confirmation (elicitation) section.
  • contentHash(value) -- SHA-256 of the key-sorted JSON of value; the confirmation state is bound to the hash of the exact validated arguments.
  • ToolResult (type) -- Standard tool return type with content array, optional structuredContent, and isError flag.
  • ToolAnnotations (type) -- MCP tool annotations: readOnlyHint, destructiveHint, idempotentHint, openWorldHint.
  • ToolScope (type) -- Tool scope enum: "NS" (namespace-scoped), "SYS" (system-scoped), "NONE" (no namespace), "BOTH".
  • PaginateResult<T> (type) -- Generic result type for paginated tool responses: items array, nextCursor, and hasMore flag.
  • buildToolContext() -- Factory function to create a ToolContext from an HTTP client and Atelier version.
  • encodeCursor() / decodeCursor() -- Cursor encoding utilities for paginated tool responses.
  • resolveTransport() -- Returns stdio from --transport / MCP_TRANSPORT, and throws a configuration error for any other configured value.

Atelier API Utilities

  • negotiateVersion() -- Negotiates the best Atelier API version supported by the connected IRIS instance.
  • requireMinVersion() -- Validates that the Atelier version meets a minimum requirement for a given tool.
  • atelierPath() -- Constructs Atelier REST API URL paths with version and namespace.

Health Check

  • checkHealth() -- Performs a full health check (connection, authentication, Atelier API).
  • ping() -- Lightweight connectivity check.

Error Classes

  • IrisConnectionError -- Thrown when the IRIS server cannot be reached (network errors, DNS failures).
  • IrisApiError -- Thrown when the IRIS server returns an HTTP error (4xx/5xx). Includes statusCode and response body.
  • McpProtocolError -- Thrown for MCP protocol-level issues (invalid tool calls, schema validation failures).

Bootstrap

  • bootstrap() -- Auto-deploys the custom REST service (ExecuteMCPv2.REST.Dispatch) to IRIS on first connection. It reads the version marker stamped into the deployed ExecuteMCPv2.Setup class and orders it against the embedded BOOTSTRAP_VERSION (<semver>+<sequence>.<hash>; semver first, then sequence). An absent deployment gets the full install and an older one (including a bare 12-character hash from a build that predates the sequence) is redeployed and recompiled. A newer or foreign deployment (same semver and sequence with another hash, dev, or an unparseable value) is never redeployed: nothing is uploaded or compiled, and one [WARN] names both markers and the remedy. Only a provably absent ExecuteMCPv2.Setup class (its Atelier document route answers 404) gets the install: a marker that cannot be read while the class exists is unknown, and nothing is deployed over it either (one [WARN] names the failure and the remedy). The marker is read again immediately before each compile. A server built before this release still redeploys over a newer deployment, so every client that shares an instance is upgraded together. When the IPM-only class ExecuteMCPv2.InstallGuard is present (its Atelier document answers 200), IPM installed the classes and owns them: a deployment that would write (older, installed but not configured, or no Setup class) writes nothing from the moment the guard is seen, at startup or at the re-check before a compile, one [WARN] names the zpm commands, and BootstrapResult.ipmOwned is true (the key is absent otherwise). A read of the guard document that fails other than with a 404 is unknown, and nothing more is written either.
  • probeCustomRest() -- Reads the deployed marker and the web application registration and reports missing, current, unconfigured, stale (an older deployment), newer, foreign or unknown (no marker could be read, and the Setup class is not provably absent).
  • classifyDeployedMarker() / parseBootstrapMarker() -- The ordering of two markers (current, older, newer or foreign) and the parse of one, shared by the probe and the live gates.
  • deployClasses() -- Deploys ObjectScript classes to IRIS via the Atelier PUT /doc API.
  • compileClasses() -- Compiles deployed classes via the Atelier compile API.
  • configureWebApp() -- Creates or updates the web application for the custom REST endpoint.
  • MANUAL_INSTRUCTIONS -- Instructions for manual bootstrap when auto-bootstrap fails.
  • getBootstrapClasses() -- Returns the list of ObjectScript classes to deploy.
  • BOOTSTRAP_CLASSES -- Array of bootstrap class definitions (name + content).
  • BootstrapClass / BootstrapResult (types) -- Type definitions for bootstrap operations.

Logging

  • logger -- Shared logger instance for consistent log output across all servers.
  • Logger (type) -- Logger interface type.
  • LogLevel / parseLogLevel() -- Log level enum and parser.

Zod Helpers

  • booleanParam -- Zod schema for boolean parameters that also accepts string/number values ("true"/"false", 1/0).

Tool Visibility (advertise-time preset filter)

tool-visibility.ts implements the config-driven, advertise-time tool-visibility engine (the IRIS_TOOLS_PRESET / IRIS_TOOLS_DISABLE / IRIS_TOOLS_ENABLE family) applied by McpServerBase at construction, in FRONT of call-time governance — described in the suite's Tool Visibility Presets section. A hidden tool is never registered with the SDK (absent from tools/list, uncallable), so it is orthogonal to governance (which controls whether an already-visible action is allowed).

  • parseToolVisibilityConfig() -- Parses the visibility env family into a ToolVisibilityConfig. Fails fast on an unknown preset value (naming the valid full/core/developer), a bare *, or a literal iris_server_profiles in IRIS_TOOLS_DISABLE; WARNs (never fails) on unknown tool names and on the same literal in both lists (ENABLE wins).
  • resolveVisibleTools() -- Applies resolution ENABLE > DISABLE > preset > default-visible (trailing-* wildcards) over a package's tool set, returning the visible set plus visible/hidden counts. Reserved iris_server_profiles is always visible.
  • assertPresetCoverage() -- Registration-time guard (sibling of assertGovernanceClassification): throws, naming the offending tool + preset, if any preset's include ∪ exclude ≠ the package tool-set or include ∩ exclude ≠ ∅. full is reserved (all tools).
  • TOOL_PAIRS -- Co-visibility pairs (iris_env_diff/iris_env_promote, iris_doc_get/iris_doc_edit since Story 38.4, and iris_message_search/iris_message_body since Story 39.5, and iris_test_coverage/iris_test_status since Story 40.1) that every preset must keep together-in or together-out.
  • ToolPresetName / ToolPresetRoster / ToolPresetRosters / ToolVisibilityConfig (types) -- Preset name union and the per-package include/exclude roster shapes wired via McpServerBaseOptions.toolPresets.

PHI Data Policy

data-policy.ts and hl7-redaction.ts implement the per-profile PHI data policy described in the suite's PHI data policy section: block, redact (the default) or allow, resolved at startup from the IRIS_PROFILES entry, IRIS_DATA_POLICY, the governance file's dataPolicy section, then redact. McpServerBase applies it to every profile, so a handler reads the policy that applies to the call as ctx.config.dataPolicy; the roster of iris_server_profiles reports dataPolicy and dataPolicySource. The data policy reduces exposure of message-body data; it is not a compliance certification.

  • parseOperatorDataPolicy() / resolveDataPolicy() / applyDataPolicies() / effectiveDataPolicy() -- Read IRIS_DATA_POLICY (fails fast on a malformed value), resolve one profile or a whole registry, and read the effective policy of a config. A value on the default entry is never inherited by another profile.
  • tightenDataPolicy() -- A caller can only tighten the operator's policy; the result says when a looser request was clamped.
  • BODY_KINDS / isRedactableBodyKind() / BLOCK_REASONS -- The nine body kinds ExecuteMCPv2.REST.MessageSearch.BodyKind returns (only hl7v2 is redactable) and the fixed texts that say why a body is withheld.
  • decideBodyPolicy() / BodyPolicyPlan -- The policy's decision for one body from its kind, whether it can be read and the policy (none, blocked with a fixed reason, or redact); the resend preview and iris_message_body both decide through it.
  • redactHl7() -- Fail-closed ER7 redaction: keeps only the fields of HL7_KEEP_FIELDS and redacts every other field of every segment, preserving segment order, terminators and separators. It refuses a text it cannot read and never throws. iris_message_body shows its output under redact.
  • ToolDefinition.dataPolicy (actions, phiInputs) -- Declares that a tool is under the policy and which of its inputs carry PHI; McpServerBase checks the declaration at registration, and the audit log redacts the declared inputs under redact and block.
  • REFUSAL_CODES.DATA_POLICY_BLOCKED -- The refusal for body data a policy withheld.
  • REFUSAL_CODES.MONITOR_BUSY -- The refusal for a run that needs the instance-wide Line-by-Line monitor while a session is active (Story 40.1).
  • REFUSAL_CODES.PRODUCTION_BUSY -- The refusal for a run that includes %UnitTest.TestProduction tests while a different production runs in the namespace, or while its state cannot be read (Story 40.3).
  • REFUSAL_CODES.CONFIRMATION_DECLINED -- The refusal for a gate whose confirmation dialog the person declined, dismissed, or accepted without ticking Confirm (Story 43.3). structuredContent is {code, action, response} with response decline, cancel or unconfirmed; nothing was changed, and the person is not asked again for that call. The audit entry is denied with denyReason: "CONFIRMATION_DECLINED".

Server Manager Connections & the iris-mcp-credentials CLI

server-manager-source.ts, credential-chain.ts, and cli/credentials.ts implement the suite's Server Manager connections feature (Epic 31): importing intersystems.servers definitions from VS Code Server Manager settings files instead of duplicating host/port/username into every MCP client's config. All four env vars are optional and default off/unset (unset IRIS_SERVER_MANAGER ⇒ the module is never invoked and the filesystem is never touched — the Rule #19 back-compat gate):

| Variable | Default | Purpose | |---|---|---| | IRIS_SERVER_MANAGER | off | off / auto / required. Unknown values fail fast at startup naming the valid set. | | IRIS_SM_SERVERS | unset (import all) | Comma-separated allow-list of server names to import. Set-but-empty ("", ",", whitespace) means unset — import all (RECORDED DECISION 2026-07-26, deferred item 31-3-6: this matches the suite-wide empty-string convention — IRIS_PROFILES="" is likewise treated as absent, pinned by a dedicated back-compat test — so this one variable is deliberately NOT given a divergent "set-empty means none" reading). | | IRIS_SM_SETTINGS_PATHS | unset (full discovery) | path.delimiter-separated list of settings files that REPLACES discovery (workspace .vscode/settings.json → *.code-workspace → per-product user settings). | | IRIS_SM_WORKSPACE | process CWD | Workspace directory for the workspace-scope candidates. The CWD default means the MCP client chooses which repo's .vscode/settings.json is read — see the trust decision below. | | IRIS_CREDENTIAL_HELPER | unset (link skipped) | External command run to resolve a Server Manager server's password (server name appended as its FINAL argv entry; 10s per-profile timeout, sequential per profile — a configured-but-unreachable helper can cost up to 10s × password-less profiles at startup; narrow with IRIS_SM_SERVERS. RECORDED DECISION 2026-07-26, deferred item 31-1-3: no aggregate budget in v1 — the per-link 10s timeout is AC-mandated, the feature is opt-in, and iris-mcp-credentials test validates a helper before it reaches startup). |

  • resolveServerManagerProfiles() -- Discovery + JSONC parse + mergeProfile validation, returning one tagged (resolved/unresolved) profile per unique name. Precedence is first-file-wins, always (RECORDED DECISION 2026-07-26, deferred items 31-1-2/31-3-3: a name's fate is decided at its first sighting across the precedence-ordered files and never reconsidered; a password-bearing lower-precedence definition skipped by this rule is announced with a warning naming both files' hosts and the remedy).
  • resolveCredential() / resolveServerManagerCredentials() -- The credential chain: IRIS_PROFILES.<name>.password / IRIS_PASSWORD → OS keychain (service iris-mcp, account <serverName>, via @napi-rs/keyring optionalDependency) → IRIS_CREDENTIAL_HELPER → exhausted (excluded with all remediations named; required escalates to startup failure).
  • iris-mcp-credentials bin -- set <name> (hidden prompt or --stdin, never argv), delete <name>, list [--json] (names only), test <name> [--connect] [--json] (runs the real chain and reports which link resolved). Exit codes: 0 success / 1 not-found-unresolved-or-failed-connect / 2 usage error.

Which directory do we trust? (the CWD workspace candidate). With IRIS_SM_WORKSPACE unset, the workspace candidate is derived from the server process's CWD — which the MCP client, not the operator, chooses — so a merely-cloned third-party repo's .vscode/settings.json can contribute connection profiles. RECORDED DECISION 2026-07-26 (deferred item 31-3-9, architecture decision J1 in ../../_bmad-output/planning-artifacts/architecture.md): the CWD default stays in v1/v2 (it is AC-31.0.1-mandated, and the mitigations — IRIS_SM_WORKSPACE, IRIS_SM_SERVERS, env/IRIS_PROFILES always win collisions, the candidate list logged at debug, sourceFile provenance in the iris_server_profiles roster — are all documented); requiring an explicit opt-in is a breaking change deferred to a future major. New config channels never discover from the CWD — IRIS_GOVERNANCE_FILE (Epic 32) is an explicit operator-supplied path only.


Governance File & the iris-mcp-governance CLI

governance.ts implements the policy engine (parse, seeds, the 7-step cascade including the parent-key inherited disable of Story 38.4, configSource with its parent value) and cli/governance.ts the suite's second bin — iris-mcp-governance (built to dist/cli/governance-cli.js) — the scriptable management surface for the IRIS_GOVERNANCE_FILE policy file (Epic 32). Both are opt-in: with the variable unset the servers never touch the filesystem, and the CLI is a standalone utility that changes nothing until you point it (or a server) at a file.

  • iris-mcp-governance bin — validate (the server's exact loader error text on failure), get/set/unset <key> [--profile <name>] (file-layer edits; atomic temp+rename writes with automatic post-write re-validation and rollback), preset read-only|full (prints env-level guidance — writes nothing, the preset is env-sourced only), effective [--profile] and diff (the SAME shared cascade functions the servers compute with — imported, never reimplemented), and universe [--profile <name>] [--root <path>] (Story 32.2 — the FULL governed-key universe: the frozen baseline ∪ the five server packages' registered tool keys, derived from their built dist the same way the iris-mcp-all cross-package tests and the baseline generator do, ∪ the framework iris_server_profiles tool — rendered with the REAL mutates/default-enabled classifications and parent keys, so post-foundation write keys seed default-DISABLED exactly as a running server reports; --root names a monorepo root or package container dir, otherwise the CLI auto-detects from its own install location). Default file resolution: --file wins over IRIS_GOVERNANCE_FILE; explicit path only, never discovered (architecture decision J1). check [--file <path>] [--root <path>] (Story 39.0 — every key in IRIS_GOVERNANCE and the resolved file checked against that full universe; a key that is none of them has no effect on any server, and the command exits 1 with one message per key. A running server only warns about such a key at startup, and only for the tools it registers). Exit codes: 0 success / 1 operational failure (invalid file per the server loader, key not set for unset, a key that matches nothing for check) / 2 usage error. --json on read commands emits exactly one parseable JSON object on every operational outcome, failures included. Full reference: the suite README.
  • Single-sourcing discipline. The CLI composes loadGovernanceFile, parseGovernanceConfig, parseGovernancePreset, effective, configSource, defaultSeed, getEffectivePolicy, getEffectiveConfigSources, GOVERNANCE_BASELINE, and BASELINE_ACTION_CLASSIFICATIONS from this package — a policy written by the CLI is byte-for-byte what the servers will enforce, and validate failure text is identical to a server's startup failure.
  • Caveat (post-foundation keys). effective/diff render over the frozen baseline ∪ keys mentioned in any config layer; they cannot enumerate each server's registered tool keys (importing a server package would be a circular dependency). The universe command closes that gap by deriving the registered half from built dist (it needs the packages' dist/tools/index.js locatable — monorepo layout or npm siblings); iris_server_profiles on a running server remains the authoritative render.

Audit Logging (framework surface, not part of the public barrel)

audit.ts implements the opt-in, structured, secrets-free session audit log described in the suite's Compliance & Auditability section (IRIS_AUDIT_LOG / IRIS_AUDIT_LOG_MAX_MB / IRIS_AUDIT_LOG_PARAMS). Unlike everything in Public API above, its exports (AuditLogger, parseAuditConfig(), redactValue(), AuditConfig/AuditEntryInput/AuditOutcome) are not re-exported from this package's barrel (index.ts) — the module is consumed internally, exclusively by server-base.ts.

  • AuditLogger -- Owns the per-process session UUID, a monotonic per-session seq counter, a serialized append queue (fs.appendFile, one JSONL line per call), size-based rotation (<path> → <path>.1), and degrade-never-throw semantics (a post-startup sink failure is swallowed, logged once, and counted rather than propagated into the tool path). shutdown() flushes the queue and writes a final line recording droppedEntries.
  • parseAuditConfig() -- Parses IRIS_AUDIT_LOG / IRIS_AUDIT_LOG_MAX_MB / IRIS_AUDIT_LOG_PARAMS from an injectable env. Returns undefined (auditing OFF) when IRIS_AUDIT_LOG is unset; throws naming the offending variable on a malformed IRIS_AUDIT_LOG_MAX_MB.
  • The confirmation field (Story 43.3). AuditEntryInput.confirmation is additive, set only on the entry of a call that was asked: accepted, declined, cancelled, unconfirmed or unanswered. A decline is outcome: "denied" with denyReason: "CONFIRMATION_DECLINED"; a dialog nobody answers and a call the client cancels are error entries. outcome keeps its domain.
  • redactValue() -- Pure, non-mutating recursive redaction: replaces the value of any key matching the credential-name family (password, secret, token, credential, apikey, authorization, etc. — case-insensitive) with "[REDACTED]", and truncates any other string over 2 KB.

Framework surface, not a tool (Rule #31). McpServerBase.handleToolCall — the single choke point every tool call passes through, on every server — wraps each call with a thin audit interceptor when IRIS_AUDIT_LOG is set. It is wired centrally in server-base.ts, so it automatically covers all five server packages and every present and future tool with zero per-tool code, and it appears in no package's tool array: it adds nothing to any packages/<pkg>/src/tools/index.ts array and changes no package's advertised tool count. It also carries no mutates classification and no IRIS_GOVERNANCE key — deliberately: audit logging is server configuration, not a governed tool action an AI client could switch off via governance.


Architecture

All five IRIS MCP server packages depend on @iris-mcp/shared:

@iris-mcp/dev ─────┐
@iris-mcp/admin ───┤
@iris-mcp/interop ─┼──> @iris-mcp/shared ──> InterSystems IRIS
@iris-mcp/ops ─────┤
@iris-mcp/data ────┘

The shared package provides the HTTP communication layer, MCP protocol handling, and tool registration framework. Each server package defines its own tools (name, schema, handler) and passes them to McpServerBase for registration.

@iris-mcp/shared is the only package that imports the MCP SDK. It runs on the SDK v2 server package (@modelcontextprotocol/server, pinned to an exact version), and McpServerBase serves tools/list, tools/call, prompts/get and resources/read itself, through the SDK's public setRequestHandler, so the bytes a 2025-11-25 client reads do not depend on how the SDK formats them. A tools/call is validated inside the audited call path, so a schema-invalid call writes its audit entry.

McpServerBase.start() serves stdio through the SDK's serveStdio, which serves both protocol revisions from one process: the 2025-11-25 initialize handshake and revision 2026-07-28 (server/discover with a per-request _meta envelope). One builder makes each SDK instance from the framework's state (every visible tool, the governance resources, every prompt, then the owned handlers), and the factory serveStdio calls takes the instance built at construction first, so server is the instance that serves. At the default log level, each factory call writes one [INFO] line naming the era of the message the connection opened with. The two revisions answer the same content: the 2026-07-28 wire is the 2025-11-25 wire plus the fields that revision mandates (resultType and the server identity in _meta on every result, ttlMs and cacheScope on the cacheable methods), minus the tools' execution. A per-request _meta key never changes server or namespace resolution, governance, visibility or the audit entry.

The connection flow is:

  1. Server starts and loads configuration from environment variables
  2. McpServerBase initializes the MCP transport (stdio)
  3. On first tool call, the HTTP client connects to IRIS and negotiates the Atelier API version
  4. Bootstrap compares the deployed version marker with the embedded one and installs or upgrades the custom REST classes when they are absent or older (a newer or foreign deployment is left alone with a warning)
  5. Tools execute via the Atelier REST API or custom REST endpoint as appropriate

Back to IRIS MCP Server Suite