@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
Maintainers
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 optionalsignal(Story 43.3).RequestOptions.signalis anAbortSignal: an already aborted signal sends no request and rejects with anIrisConnectionErrorof codeCANCELLED, and an abort while the request is in flight aborts it and rejects with the same code.McpServerBasepasses 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 thetools/list,tools/call,prompts/getandresources/readhandlers on top of the MCP SDK v2, and its protocol errors are SDKProtocolErrors.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 optionalconfirm(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 returnsresultunchanged whenproceedisfalse.proceedistruefor 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 aCONFIRMATION_DECLINEDrefusal that changes nothing. A context built directly (a unit test, an in-process callback) has noconfirm, and a handler treats that as no question. Ascopegiven as a function is resolved only when the client can be asked; when it throws,confirmrejects with that error and nothing is asked.ConfirmationRequest(operation,target,scope) andConfirmationOutcomeare exported as types. See the suite's Human confirmation (elicitation) section.contentHash(value)-- SHA-256 of the key-sorted JSON ofvalue; 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()-- Returnsstdiofrom--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 deployedExecuteMCPv2.Setupclass and orders it against the embeddedBOOTSTRAP_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 absentExecuteMCPv2.Setupclass (its Atelier document route answers 404) gets the install: a marker that cannot be read while the class exists isunknown, 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 classExecuteMCPv2.InstallGuardis present (its Atelier document answers 200), IPM installed the classes and owns them: a deployment that would write (older, installed but not configured, or noSetupclass) writes nothing from the moment the guard is seen, at startup or at the re-check before a compile, one[WARN]names thezpmcommands, andBootstrapResult.ipmOwnedistrue(the key is absent otherwise). A read of the guard document that fails other than with a 404 isunknown, and nothing more is written either.probeCustomRest()-- Reads the deployed marker and the web application registration and reportsmissing,current,unconfigured,stale(an older deployment),newer,foreignorunknown(no marker could be read, and theSetupclass is not provably absent).classifyDeployedMarker()/parseBootstrapMarker()-- The ordering of two markers (current,older,newerorforeign) 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 aToolVisibilityConfig. Fails fast on an unknown preset value (naming the validfull/core/developer), a bare*, or a literaliris_server_profilesinIRIS_TOOLS_DISABLE; WARNs (never fails) on unknown tool names and on the same literal in both lists (ENABLE wins).resolveVisibleTools()-- Applies resolutionENABLE > DISABLE > preset > default-visible(trailing-*wildcards) over a package's tool set, returning the visible set plus visible/hidden counts. Reservediris_server_profilesis always visible.assertPresetCoverage()-- Registration-time guard (sibling ofassertGovernanceClassification): throws, naming the offending tool + preset, if any preset'sinclude ∪ exclude≠ the package tool-set orinclude ∩ exclude ≠ ∅.fullis reserved (all tools).TOOL_PAIRS-- Co-visibility pairs (iris_env_diff/iris_env_promote,iris_doc_get/iris_doc_editsince Story 38.4, andiris_message_search/iris_message_bodysince Story 39.5, andiris_test_coverage/iris_test_statussince Story 40.1) that every preset must keep together-in or together-out.ToolPresetName/ToolPresetRoster/ToolPresetRosters/ToolVisibilityConfig(types) -- Preset name union and the per-packageinclude/excluderoster shapes wired viaMcpServerBaseOptions.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()-- ReadIRIS_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 thedefaultentry 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 kindsExecuteMCPv2.REST.MessageSearch.BodyKindreturns (onlyhl7v2is 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,blockedwith a fixed reason, orredact); the resend preview andiris_message_bodyboth decide through it.redactHl7()-- Fail-closed ER7 redaction: keeps only the fields ofHL7_KEEP_FIELDSand 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_bodyshows its output underredact.ToolDefinition.dataPolicy(actions,phiInputs) -- Declares that a tool is under the policy and which of its inputs carry PHI;McpServerBasechecks the declaration at registration, and the audit log redacts the declared inputs underredactandblock.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.TestProductiontests 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).structuredContentis{code, action, response}withresponsedecline,cancelorunconfirmed; nothing was changed, and the person is not asked again for that call. The audit entry isdeniedwithdenyReason: "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 +mergeProfilevalidation, 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 (serviceiris-mcp, account<serverName>, via@napi-rs/keyringoptionalDependency) →IRIS_CREDENTIAL_HELPER→ exhausted (excluded with all remediations named;requiredescalates to startup failure).iris-mcp-credentialsbin --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-governancebin —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]anddiff(the SAME shared cascade functions the servers compute with — imported, never reimplemented), anduniverse [--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 theiris-mcp-allcross-package tests and the baseline generator do, ∪ the frameworkiris_server_profilestool — rendered with the REALmutates/default-enabled classifications and parent keys, so post-foundation write keys seed default-DISABLED exactly as a running server reports;--rootnames a monorepo root or package container dir, otherwise the CLI auto-detects from its own install location). Default file resolution:--filewins overIRIS_GOVERNANCE_FILE; explicit path only, never discovered (architecture decision J1).check [--file <path>] [--root <path>](Story 39.0 — every key inIRIS_GOVERNANCEand 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 forunset, a key that matches nothing forcheck) / 2 usage error.--jsonon 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, andBASELINE_ACTION_CLASSIFICATIONSfrom this package — a policy written by the CLI is byte-for-byte what the servers will enforce, andvalidatefailure text is identical to a server's startup failure. - Caveat (post-foundation keys).
effective/diffrender 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). Theuniversecommand closes that gap by deriving the registered half from built dist (it needs the packages'dist/tools/index.jslocatable — monorepo layout or npm siblings);iris_server_profileson 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-sessionseqcounter, 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 recordingdroppedEntries.parseAuditConfig()-- ParsesIRIS_AUDIT_LOG/IRIS_AUDIT_LOG_MAX_MB/IRIS_AUDIT_LOG_PARAMSfrom an injectableenv. Returnsundefined(auditing OFF) whenIRIS_AUDIT_LOGis unset; throws naming the offending variable on a malformedIRIS_AUDIT_LOG_MAX_MB.- The
confirmationfield (Story 43.3).AuditEntryInput.confirmationis additive, set only on the entry of a call that was asked:accepted,declined,cancelled,unconfirmedorunanswered. A decline isoutcome: "denied"withdenyReason: "CONFIRMATION_DECLINED"; a dialog nobody answers and a call the client cancels areerrorentries.outcomekeeps 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:
- Server starts and loads configuration from environment variables
McpServerBaseinitializes the MCP transport (stdio)- On first tool call, the HTTP client connects to IRIS and negotiates the Atelier API version
- 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)
- Tools execute via the Atelier REST API or custom REST endpoint as appropriate