baikai-mcp (empty) → 0.1.0.0
raw patch · 31 files changed
+11606/−0 lines, 31 filesdep +aesondep +asyncdep +baikai
Dependencies added: aeson, async, baikai, baikai-mcp, base, base64-bytestring, bytestring, case-insensitive, containers, crypton, http-client, http-client-tls, http-types, memory, network, network-uri, process, regex-tdfa, scientific, stm, tasty, tasty-hunit, text, time, vector, wai, warp
Files
- CHANGELOG.md +3184/−0
- LICENSE +30/−0
- README.md +3/−0
- baikai-mcp.cabal +136/−0
- src/Baikai/Mcp/Auth.hs +937/−0
- src/Baikai/Mcp/Client.hs +993/−0
- src/Baikai/Mcp/Content.hs +37/−0
- src/Baikai/Mcp/Error.hs +117/−0
- src/Baikai/Mcp/Internal/Binding.hs +103/−0
- src/Baikai/Mcp/Internal/Http.hs +224/−0
- src/Baikai/Mcp/Internal/Mux.hs +137/−0
- src/Baikai/Mcp/Internal/Sse.hs +104/−0
- src/Baikai/Mcp/JsonSchema.hs +491/−0
- src/Baikai/Mcp/Prompt.hs +160/−0
- src/Baikai/Mcp/Protocol.hs +685/−0
- src/Baikai/Mcp/Resource.hs +231/−0
- src/Baikai/Mcp/Tool.hs +445/−0
- src/Baikai/Mcp/Transport.hs +356/−0
- src/Baikai/Mcp/Transport/HttpSse.hs +178/−0
- src/Baikai/Mcp/Transport/Stream.hs +175/−0
- test/AuthSpec.hs +543/−0
- test/ClientSpec.hs +189/−0
- test/JsonSchemaSpec.hs +108/−0
- test/LegacySpec.hs +192/−0
- test/Main.hs +28/−0
- test/McpStub.hs +305/−0
- test/ModernHttpSpec.hs +242/−0
- test/ProtocolSpec.hs +202/−0
- test/ResourcePromptSpec.hs +261/−0
- test/StreamSpec.hs +428/−0
- test/ToolSpec.hs +382/−0
+ CHANGELOG.md view
@@ -0,0 +1,3184 @@+# Changelog++All notable changes to baikai are recorded here.++The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and+this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).++## [Unreleased]++### Added++- `baikai-kit` skills can ship a native `codex.rules` file. Install with+ `--with-codex-rules` to activate its command rules at project or user+ scope and manage them through status, update, and uninstall.++## [baikai-mcp 0.1.0.0] - 2026-11-30++### Added++- First release, built against `baikai ^>=0.11.0.0`.+- `Baikai.Mcp.Client`, `Baikai.Mcp.Protocol`, `Baikai.Mcp.Transport`: an MCP+ client for revision 2026-07-28 over stateless Streamable HTTP, with+ handshake-era Streamable HTTP (2025-03-26 to 2025-11-25) and the deprecated+ 2024-11-05 HTTP+SSE transport (`Baikai.Mcp.Transport.HttpSse`) as explicit+ profiles. A composable request hook approves every transmission. Failures+ carry a `NotSent`/`Answered`/`Uncertain` delivery state. State-only interim+ results are continued under a round limit. Pages, drains and+ `subscriptions/listen` streams are bounded.+- `Baikai.Mcp.Tool`: tool discovery with `x-mcp-header` validation,+ descriptor-bound invocation with parameter mirrors, descriptor-drift+ reporting, rich results and projection into Baikai tool results.+- `Baikai.Mcp.JsonSchema`: a fuel-bounded JSON Schema 2020-12 validator that+ never fetches references and reports unsupported contracts as unverifiable.+- `Baikai.Mcp.Auth`: static credential references and delegated OAuth 2.1+ with PKCE, RFC 9207 issuer validation, issuer-bound registrations and+ grants, serialized refresh and an optional loopback authorizer.+- `Baikai.Mcp.Resource`, `Baikai.Mcp.Prompt`, `Baikai.Mcp.Content`:+ resources, templates, reads, resource updates, prompts and explicit+ projection.+- `Baikai.Mcp.Transport.Stream`: the same client over a caller-owned byte+ stream (stdio), with era probing and `notifications/cancelled`.++## [baikai 0.11.0.0] - 2026-11-23++### Added++- Add `anthropic_claude_fable_5_2` on Claude Messages with adaptive thinking,+ client function tools, and structured output for eligible organizations.+ Standard rates per million tokens are $8 input, $40 output, $0.20 cache+ read, $10 five-minute cache write, and $16 one-hour cache write. Fast mode+ doubles those rates.+- Add `openai_gpt_6_2_astra` and `openai_gpt_6_2_sol` on OpenAI Responses+ with structured output, function tools, and Standard pricing for both+ cache durations and long-context requests.+- Add `openai_gpt_6_1_terra` on OpenAI Responses with explicit reasoning+ and cache compatibility, 30-minute and 12-hour cache-write prices, and+ whole-request pricing above 272,000 input tokens.++### Changed (breaking)++- `AssistantContent` changes its `Generic` representation to carry original+ Responses items. `AssistantText` and `AssistantToolCall` are bundled pattern+ synonyms. Existing persisted content still decodes.++### Fixed++- Apply the published long-context tier for GPT-5.6 Sol, its `gpt-5.6`+ alias, GPT-5.6 Terra, and GPT-5.6 Luna. Use the published one-hour write+ rates for eight Claude bindings that used the five-minute rate.++## [baikai-claude 0.7.3.1] - 2026-11-23++### Changed++- Use `claude-hs 0.1.0.0` for the Messages transport and require+ `baikai ^>=0.11.0.0`. Fable 5.2 tool continuations preserve signed+ thinking, including empty signed blocks.++### Fixed++- Reject unsupported assistant prefills before dispatch. Claude 4.5 accepts+ prefills with effective thinking off. Normal tool-result continuations+ preserve prior assistant history.++## [baikai-openai 0.7.4.0] - 2026-11-23++### Added++- Expose `Baikai.Provider.OpenAI.HookEvidence` for Codex app-server clients+ to verify a reviewed pre-tool handler and decode its completion outcome.+- Add scoped Codex batch completion with reviewed PreToolUse hooks and+ native denial evidence.++### Changed++- Require `baikai ^>=0.11.0.0` for persisted Responses replay.++### Fixed++- Preserve completed Responses message and function-call items in stateless+ history. GPT-6.2 keeps reusable system prompts at the head of the input+ across tool turns.++## [baikai-typesafe 0.1.0.2] - 2026-11-23++### Changed++- Build against `baikai ^>=0.11.0.0`.++## [baikai-trace-otel 0.4.1.2] - 2026-11-23++### Changed++- Build against `baikai ^>=0.11.0.0`.++## [baikai-effectful 0.5.0.1] - 2026-11-23++### Changed++- Build against `baikai ^>=0.11.0.0`.++## [baikai-kit 0.4.0.4] - 2026-11-23++### Changed++- Build against `baikai ^>=0.11.0.0`.++## [baikai-agent 0.3.0.0] - 2026-11-23++### Added++- `baikai agent review-codex-hooks` presents exact native declarations for+ approval. `baikai agent run --codex-hooks` reports denials from the+ checked app-server thread in the JSON result.++### Changed (breaking)++- `AgentCliCommand` gains `AgentReviewCodexHooks`. Add that case to+ exhaustive matches. The runner requires `baikai ^>=0.11.0.0` and+ `baikai-openai ^>=0.7.4.0`.++## [baikai-openai 0.7.3.1] - 2026-11-14++### Fixed++- Require `baikai ^>=0.10.1.1` in library and tests so new adapter consumers+ receive the Codex final-message correction.++## [baikai 0.10.1.1] - 2026-11-14++### Fixed++- `baikai`: the Codex batch parser returns the last completed agent message+ instead of concatenating complete messages, preserving structured JSON after+ intermediate commentary. Started and updated items cannot replace the final+ answer; usage and thread observations still cover the whole run ([BUG-2](docs/bug-reports/codex-concatenates-complete-agent-messages.md)).++## [baikai 0.10.1.0] - 2026-11-03++### Added++- `Baikai.Trace.withTraceFold` and `withTraceFoldWith` own tracing across the+ entire consumer fold; `withTraceList` and `withTraceListWith` collect events.+ A healthy sink receives abort evidence before cancellation propagates,+ including cancellation between stream steps.++### Fixed++- `withTrace`, `withTraceWith`, and the traced call in `runRequestWith` and+ `runRequestWithRegistry` now finalize synchronously on cancellation. Cleanup+ resumes an interrupted terminal drain within the same one-second budget,+ preserves the original exception, and never duplicates terminal evidence.+ General-stream abandonment keeps its garbage-collection-eventual contract.++## [baikai-effectful 0.5.0.0] - 2026-11-03++### Added++- `streamCollectTraced` delegates traced event collection to core with bounded+ cleanup on cancellation. Re-export `TraceSink` for operation signatures.++### Changed (breaking)++- `Baikai` gains `StreamCollectTraced`. Third-party interpreters must handle+ this constructor. The binding requires `baikai ^>=0.10.1`.++## [baikai 0.10.0.0] - 2026-10-25++### Added++- `ThinkingNone` (`none`) explicitly requests reasoning off; `Nothing` still+ leaves provider defaults untouched. Anthropic compatibility records declare+ `supportsThinkingDisabled`; legacy records conservatively default to False.+- Endpoint-specific `NativeCachePolicy` records distinguish modern, legacy and+ unsupported native OpenAI cache controls. Policies survive legacy JSON and+ catalog refresh; Luna Responses Long has verified 12h base and tier rates.+- Evidence schema 2.8 includes the `none` preference and content-free native+ cache controls and input structure. Digest rules and the separation of+ requested, translated and observed reasoning are unchanged.++### Changed (breaking)++- `ThinkingLevel` gains `ThinkingNone` as its least constructor. Update exhaustive+ matches. Anthropic and OpenAI compatibility records gain fields; use the+ default records or update explicit record construction.+- All seven dependent packages now require `baikai ^>=0.10.0` and release+ independently below. The unchanged adapters take dependency-only patch bumps.++## [baikai-claude 0.7.3.0] - 2026-10-25++### Added++- Export `injectSystemCacheControl` for shared system-prefix cache markers.+- `ThinkingNone` sends catalog-gated `thinking: {"type": "disabled"}` without+ effort, display or a budget. Unsupported off requests remain visible+ adjustments and fail strict evidence before dispatch. A host with no thinking+ controls is not assumed to be a non-reasoning model.++### Fixed++- Short and long `cacheRetention` mark non-empty system prompts so fresh+ conversations with different first questions can reuse the tools-and-system+ prefix. System, last-tool and automatic markers share the effective TTL,+ including host downgrades, and use at most three breakpoints. Empty or absent+ system prompts and disabled caching keep their existing shape. Regression+ coverage includes tool compatibility and an isolated live shared-prefix case.+ Implements issue #2 and the approach in PR #3.++### Changed++- Require `baikai ^>=0.10.0`.++## [baikai-openai 0.7.3.0] - 2026-10-25++### Added++- Export `applyNativeCache` for validated native cache plans.+- OpenAI-compatible Chat (including Ollama) and Responses carry `none` where+ supported. Z.ai and Qwen emit `enable_thinking: false`; unsupported off+ requests remain visible adjustments and fail strict evidence before dispatch.++### Fixed++- Native OpenAI Short caching marks shared non-empty system prefixes on+ catalog-supported Responses and Chat bindings. Unsupported native requests+ fail locally. Effective duration reaches terminal pricing, partial usage+ and evidence.+- Funded live prefix checks pass for Luna Responses Short/Long and GPT-5.6 Chat+ Short. Luna Long uses verified 12h base and tier rates; unsupported Chat Long+ and unverified modern bindings remain locally refused.++### Changed++- Require `baikai ^>=0.10.0`. Catalog effort policies distinguish GPT-5/o-series+ models that cannot disable reasoning, Sol/Luna that accept none, and+ Astra/GPT-6.1 Sol that do not.++## [baikai-typesafe 0.1.0.1] - 2026-10-25++### Changed++- Require `baikai ^>=0.10.0`. Dependency-only update; no package API change.++## [baikai-trace-otel 0.4.1.1] - 2026-10-25++### Changed++- Require `baikai ^>=0.10.0`. Dependency-only update; no package API change.++## [baikai-effectful 0.4.0.5] - 2026-10-25++### Changed++- Require `baikai ^>=0.10.0`. Dependency-only update; no package API change.++## [baikai-kit 0.4.0.3] - 2026-10-25++### Changed++- Require `baikai ^>=0.10.0`. Dependency-only update; no package API change.++## [baikai-agent 0.2.0.4] - 2026-10-25++### Fixed++- Layered job configuration accepts `thinking "none"` through the shared+ canonical parser, keeping explicit off distinct from an absent preference.+- The UTF-8 stdin test runs in a child process under an ASCII locale, avoiding+ shared-stdin descriptor races with parallel subprocess tests in the tarball.++### Changed++- Require `baikai ^>=0.10.0`, `baikai-claude ^>=0.7.3` and+ `baikai-openai ^>=0.7.3` for explicit-off handling in both vendor renderers.++## [baikai 0.9.0.0] - 2026-10-25++### Added++- `Baikai.Judgment` compiles closed-set schemas into ordered questions, refuses+ generation controls and validates neutral answers without normalizing provider+ probabilities or deriving confidence and expected scores.+- `UserData`, `AssistantData`/`DataContent`, user-data message helpers, atomic+ data events, and named full-response JSON codecs preserve structured answers.+- `TypeSafeSystemOne`, catalog-owned `OutputKind`/`isJudgmentOnly`, `InputData`,+ and `typesafe_jev_latest`/`typesafe_jev_preview`. Legacy model JSON defaults to+ generative output. Register the new `baikai-typesafe` provider explicitly.++### Changed (breaking)++- Public content/event sums and model, error, trace and log records gain fields+ or constructors. Update exhaustive matches and record construction on upgrade.+- Terminal traces and both call-log paths preserve structured answer payloads.+ Evidence schema 2.6 includes structured response commitments and typed request+ problems; existing digest rules are unchanged.++## [baikai-typesafe 0.1.0.0] - 2026-10-25++### Added++- Initial explicitly registered TypeSafe System One provider using the released+ `typesafe-hs ^>=0.1.0.0` wire client. Strict request and response validation,+ atomic synthetic streaming, truthful call evidence, bounded HTTP calls and an+ opt-in live test. No retry policy is embedded.+- Installation, schema, refusal and consumer migration guide, plus CAP-27.++## [baikai-claude 0.7.2.0] - 2026-10-25++### Changed++- Require `baikai ^>=0.9.0`, encode user data as canonical JSON text, and refuse+ structured assistant history before dispatch with a typed field path.++### Fixed++- The offline cancellation fixture waits until the response reader is active+ before cancelling, eliminating a fixed-startup-delay race under build load.++## [baikai-openai 0.7.2.0] - 2026-10-25++### Changed++- Require `baikai ^>=0.9.0`, encode user data as canonical JSON text, and refuse+ structured assistant history before dispatch with a typed field path across+ Chat Completions, Responses and batch CLI calls.++### Fixed++- The offline cancellation fixture waits until the response reader is active+ before cancelling, eliminating a fixed-startup-delay race under build load.++## [baikai-trace-otel 0.4.1.0] - 2026-10-25++### Added++- Export structured answer data as canonical JSON under+ `baikai.response.structured_data`, on success and failure terminals.++### Changed++- Require `baikai ^>=0.9.0` for the expanded trace protocol.++## [baikai-effectful 0.4.0.4] - 2026-10-25++### Changed++- Require `baikai ^>=0.9.0`. Dependency-only update; no package API change.++## [baikai-kit 0.4.0.2] - 2026-10-25++### Changed++- Require `baikai ^>=0.9.0`. Dependency-only update; no package API change.++## [baikai-agent 0.2.0.3] - 2026-10-25++### Changed++- Require `baikai ^>=0.9.0`. Dependency-only update; no package API change.++## [baikai 0.8.0.0] - 2026-10-10++### Added++- Catalog: `anthropic_claude_haiku_5_5` (Claude Haiku 5.5, released+ 2026-10-07). It uses Messages with adaptive thinking, drops sampling options,+ forwards forced tool choice, and has a 1,000,000-token context and+ 128,000-token output limit. Prompts over 100,000 tokens, counting cache reads+ and writes, are priced at $0.50/$0.05/$0.625/$2.50 per million input, cache+ read, cache write and output tokens instead of $0.10/$0.01/$0.125/$0.50, and+ one-hour cache writes at $1 instead of $0.20. Live text and tool cases+ passed on 2026-10-10, and a live request confirmed forced tool choice with+ adaptive thinking.++### Changed (breaking)++- `Baikai.Model.InputPriceTier` gains a third field, `longCacheWriteCost ::+ Maybe Rational`: the one-hour cache-write rate for requests that cross that+ tier. `resolveRates` now takes the long rate from the selected tier rather+ than overriding every tier with the policy-level rate, and validation rejects+ a policy whose policy-level long rate leaves any tier without one. Tier JSON+ without the key decodes as `Nothing`. __Breaking__: positional constructions+ of `InputPriceTier` need the new argument.++### Changed++- Catalog: the 2026-10-10 model refresh lowers `anthropic_claude_sonnet_5_5`'s+ cache-read rate from $0.20 to $0.10 per million tokens, following Anthropic's+ 2026-10-07 price cut, and corrects `anthropic_claude_sonnet_4_5`'s context+ window from 1,000,000 to 200,000 tokens (its 1M beta ended on 2026-04-30).+ Claude Haiku 5.5 was curated separately (see Added). No OpenAI model was+ added.++- Documentation: the 2026-10-02 model refresh found no new OpenAI or Anthropic+ models; the catalog is unchanged. `docs/user/models-and-providers.md` notes+ Anthropic's retirement of Claude Sonnet 4.5 on 2026-11-30 (deprecation of+ `anthropic_claude_sonnet_4_5` is planned in plan 89 for a future release;+ it remains in 0.8.0.0),+ why the access-gated Claude Mythos models are not curated, and how GPT-6+ Astra's new ultrafast service tier is costed.++### Fixed++- The shared batch subprocess scope now owns POSIX process groups, joins pipe+ readers, and synchronously reaps direct children before acknowledging+ cancellation. Executable-version probes use the same scope. Darwin/Linux+ coverage excludes processes that deliberately escape the group and adopted+ descendant reaping; Windows retains direct-child cleanup. The provider fixes+ ship in `baikai-claude 0.7.1.1` and `baikai-openai 0.7.1.1`; see+ [plan 90](docs/plans/90-terminate-owned-batch-cli-process-groups-before-acknowledging-cancellation.md)+ and [BUG-1](docs/bug-reports/batch-cli-cancellation-leaves-child-alive.md).++- `baikai`'s source distribution now ships `data/models/*.json` and the test+ suite's fixtures under `test/fixtures/`. Without them, running the suite from+ the Hackage tarball failed 27 of 794 tests on missing files: the fixtures+ themselves, plus the catalog round-trip test, whose `baikai-gen-models` run+ had no model data to read.++## [baikai-claude 0.7.1.1] - 2026-10-10++### Fixed++- Batch `claude -p` calls stop owned POSIX process-group members and join pipe+ readers before acknowledging cancellation, including active synthetic streams+ and evidence probes. Preserves the original asynchronous exception. Resolves+ [BUG-1](docs/bug-reports/batch-cli-cancellation-leaves-child-alive.md).++### Changed++- Requires `baikai ^>=0.8.0` for shared subprocess ownership and the new pricing+ tier field. No provider API change. Haiku 5.5 request contracts are covered+ by offline tests.++## [baikai-openai 0.7.1.1] - 2026-10-10++### Fixed++- Batch `codex exec` calls stop owned POSIX process-group members and join pipe+ readers before acknowledging cancellation, including active synthetic streams,+ repeated cancellation, and evidence probes. The temporary schema survives+ until subprocess cleanup finishes. Resolves+ [BUG-1](docs/bug-reports/batch-cli-cancellation-leaves-child-alive.md).++### Changed++- Requires `baikai ^>=0.8.0` for shared subprocess ownership and the new pricing+ tier field. No provider API change.++## [baikai-trace-otel 0.4.0.2] - 2026-10-10++### Changed++- Requires `baikai ^>=0.8.0` for compatibility with the core pricing tier+ change. No package API change.++## [baikai-effectful 0.4.0.3] - 2026-10-10++### Changed++- Requires `baikai ^>=0.8.0` for compatibility with the core pricing tier+ change. No package API change.++## [baikai-kit 0.4.0.1] - 2026-10-10++### Changed++- Requires `baikai ^>=0.8.0` for compatibility with the core pricing tier+ change. No package API change.++## [baikai-agent 0.2.0.2] - 2026-10-10++### Changed++- Requires `baikai ^>=0.8.0` for compatibility with the core pricing tier+ change. No package API change.+- Raises the provider bounds to `baikai-claude ^>=0.7.1.1` and+ `baikai-openai ^>=0.7.1.1`, so installing the tool selects the fixed batch+ adapters. Binary regressions use the shared process fixture and cover both+ cancellation and a 1MiB output flood.++## [baikai-kit 0.4.0.0] - 2026-10-02++### Added++- Per-item `visibility` (`tool-only` by default, or `shared`) for manifest+ versions 1 and 2, with `kit install --shared`, `--tool-only`, and+ `--accept-shared-codex`. Shared Claude skills and agents use tracked links;+ tool-only Codex skills use tracked disabled entries in `config.toml`.+- `codexSessionArgs`, required in the `extraArgs` of a consumer's own Codex+ launches to re-enable its tool-only skills. This is the one launcher step+ beyond a dependency bump; the standard `kitConfig`/`kitCommandParser`/`runKit`+ integration otherwise compiles unchanged. Codex custom agents cannot be+ isolated and require explicit acceptance, or shared visibility.+- Requested and effective visibility in status (table and JSON), the+ `visibility-broken` condition, and a migration note for legacy shared Codex+ skills. Update repairs visibility even for items skipped for local edits;+ uninstall removes only owned links and config entries.++### Changed (breaking)++- `SkillEntry` and `AgentEntry` gain `visibility`; `SidecarMeta` gains+ `visibility`, `visibilitySource`, `sharedLinks`, and `codexDisabledSkills`;+ `newSidecarMeta` takes these values. `RemovalOutcome` gains `linksRemoved`+ and `configEntriesRemoved`; `StatusRow` gains `requestedVisibility` and+ `effectiveVisibility`; `KitConfig` gains `confirmSharedCodex` (default+ `Nothing` in `kitConfig`).+- `KitInstall` gains `InstallOptions`; `installItem` and `installFrom` take+ it as their last argument. Use `defaultInstallOptions` to follow the+ manifest. Explicit install flags persist across updates, while new+ manifest-driven installs follow updated defaults. Legacy placement is kept.+- JSON adds list `visibility`, status `requestedVisibility` and+ `effectiveVisibility`, and the new condition value. `formatVersion` stays+ 1 because all additions preserve existing keys and their meaning.++### Fixed++- Codex installs refuse destinations without this tool's sidecar instead of+ overwriting user or other-tool assets. Uninstall also preserves foreign+ Codex assets. Shared Claude names are checked before any provider write.+- Codex config edits preserve UTF-8 text, comments and permissions, refuse+ symlinks and invalid/conflicting config, and verify the semantic change+ before atomic rename. Reused user-owned disabled entries survive uninstall.+ Shared visibility refuses a user-owned entry that would keep the skill hidden.+- The source distribution ships the test suite's manifest fixtures and JSON+ goldens, so the test suite passes when run from the Hackage tarball. Since+ 0.3.0.0 it had failed there, because those files were missing.++## [baikai 0.7.2.0] - 2026-09-30++### Added++- Curated GPT-6.1 Sol on OpenAI Responses and Claude Sonnet 5.5 on Anthropic+ Messages (`openai_gpt_6_1_sol`, `anthropic_claude_sonnet_5_5`), with endpoint+ compatibility facts, standard prices, GPT-6.1 Sol's 272K-token context tier,+ and Sonnet 5.5's one-hour cache-write rate. Sonnet 5.5 rejects forced tool+ choice locally and has no fast mode. Both passed live text and function-tool+ acceptance on 2026-09-30 through `/v1/responses` and `/v1/messages`+ ([record](docs/validation/plan-85/2026-09-30-complete.json),+ [plan 85](docs/plans/85-prove-gpt-6-1-sol-and-claude-sonnet-5-5-live-compatibility.md)).+ The focused smoke runner gains the `sol61-*` and `sonnet55-*` cases.+- `Baikai.ResponseFormat.StructuredOutputSupport`+ (`NativeJsonSchema | NoStructuredOutput`), `declaredStructuredOutput :: Api ->+ StructuredOutputSupport`, and a `structuredOutput` field on `ApiProvider`+ (default `NoStructuredOutput` in `apiProviderWith`), so a caller can ask+ whether a transport enforces a schema without calling it. Every built-in+ provider declares `NativeJsonSchema`.++## [baikai-claude 0.7.1.0] - 2026-09-30++Requires `baikai >=0.7.2`.++### Added++- `claude -p` honours a `JsonSchema` response format (IR-11): it receives+ `--json-schema '<schema>'` and the response text is the tool's validated+ `structured_output`. A missing `structured_output` is a `DecodeFailure`; a+ `claude` too old for the flag yields an `InvalidRequest` error with the exit+ code rather than unconstrained text. `JsonObject`, `name` and `strict` are not+ forwarded; requests without a schema render the same argument vector as+ before. Both Claude providers declare `structuredOutput = NativeJsonSchema`.++### Fixed++- Anthropic adaptive `ThinkingHigh` now sends+ `output_config.effort: "high"` instead of omitting the field. Claude Opus 5.5+ defaults to `medium`, so it previously ran `ThinkingHigh` at medium effort;+ other adaptive models default to `high` and behave as before. Evidence for+ these calls records `effortText = "high"` and no longer carries+ `effort_omitted`, so strict evidence mode no longer refuses them.+ `Baikai.Evidence.EffortOmitted` stays exported, and older records still decode.++## [baikai-openai 0.7.1.0] - 2026-09-30++Requires `baikai >=0.7.2`.++### Added++- `codex exec` honours a `JsonSchema` response format (IR-11): the schema is+ written to a temporary file passed as `--output-schema <file>` and deleted+ however the call ends. A `codex` too old for the flag yields an+ `InvalidRequest` error with the exit code rather than unconstrained text.+ `JsonObject`, `name` and `strict` are not forwarded; requests without a schema+ render the same argument vector as before. All three OpenAI providers declare+ `structuredOutput = NativeJsonSchema`.+- `codexCliCommandWith`, which renders the `codex exec`+ vector with a given `--output-schema` file. `codexCliCommand` is unchanged+ and never renders the flag.++## [baikai 0.7.1.0] - 2026-09-23++### Added++- Curated GPT-6 Sol and Luna on OpenAI Responses and Claude Opus 5.5 on+ Anthropic Messages (`openai_gpt_6_sol`, `openai_gpt_6_luna`,+ `anthropic_claude_opus_5_5`), with endpoint compatibility and standard,+ long-context, cache-duration, and fast-mode prices where applicable. All+ three passed live acceptance on 2026-09-23. Sol and Luna dispatch to+ `OpenAIResponses`, so calling them requires the+ `Baikai.Provider.OpenAI.Responses.register` call that `baikai-openai 0.7.0.0`+ introduced.++## [baikai-kit 0.3.0.0] - 2026-09-23++Closes four improvement requests from the tools that ship `baikai-kit` as their+`kit` command: project scope resolves from a configurable root (IR-8),+`kit status` reports local edits separately from upstream drift (IR-7),+`kit install` without a name asks a tool-supplied chooser (IR-6), and `list`,+`status` and `update` print versioned JSON (IR-9). A consumer raising its bound+builds `KitConfig` with `kitConfig`, passes it to `kitCommandParser`, and+matches on `StatusRow.conditions`; each break is at a call site the compiler+names.++### Added++- `baikai-kit`: `KitConfig.projectRoot :: IO FilePath` says where project scope+ lives. Install, status, update, uninstall and `agentDirsForSession` all derive+ project-scope paths from it, so they agree whichever subdirectory a command+ runs from. `kitConfig` builds a configuration with every optional field at its+ default (project scope is the current directory, as before);+ `projectRootByMarkers [".git", ".mytool"]` is a ready-made resolver that walks+ up to the nearest marker and falls back to the current directory, and+ `findProjectRoot` is the underlying walk. Resolves IR-8.++- `baikai-kit`: `kit status` reports local edits. It runs the same+ installed-file check `kit update` uses to skip an item, and shows+ `modified` for an edited copy and `edits-unknown` for one whose sidecar+ predates the installed-file hash. The check is exported as+ `checkLocalEdits`, returning `LocalEdits` (`Unedited`, `Edited`,+ `EditsUnknown`). Resolves IR-7.++- `baikai-kit`: `kit install` with no name asks a chooser the tool supplies in+ the new `KitConfig.chooseItem :: Maybe (KitManifest -> IO (Maybe Text))`+ field. The engine refreshes the kit, passes the whole manifest, and installs+ what the chooser returns; a cancelled choice prints+ `No item chosen; nothing installed.` and exits 0. With no chooser (the+ `kitConfig` default) the command fails with the new `KitItemNameRequired`+ error, which tells the user to pass `NAME`. The engine ships no picker.+ `KitCommand` derives `Eq`, and `kit install --help` names the tool's+ `.<tool>/agents` directory. Resolves IR-6.++- `baikai-kit`: `kit list`, `kit status` and `kit update` accept `--json` and+ print exactly one versioned JSON document on stdout+ (`{"formatVersion": 1, "document": "kit-list" | "kit-status" | "kit-update", …}`);+ warnings and the first-clone notice go to stderr, and a failed command writes+ nothing to stdout. The shapes are written by explicit encoders —+ `Baikai.Kit.Json.listDocument`, `statusDocument`, `updateDocument`, and+ `kitJsonFormatVersion` — so library callers get the same values, and they are+ pinned by golden tests. `Baikai.Kit.Command.OutputFormat` selects the mode,+ and `Baikai.Kit.Status.InstalledCopy` / `installedCopies` report where each+ item is installed. Resolves IR-9.++### Changed++- `baikai-kit`: `KitConfig` gains the strict field `projectRoot`, so a record+ literal must set it; build the configuration with+ `kitConfig toolName repoUrl providers` instead and override fields with record+ update syntax. `KitConfig`'s `Show` instance is now hand-written and prints+ `<IO FilePath>` for the resolver. __Breaking__.++- `baikai-kit`: `kit status` conditions compose, and `dirty` is renamed+ `changed-upstream` (it meant the upstream sources changed without a version+ bump, not local edits); `dirty+outdated` now reads+ `outdated+changed-upstream`. `StatusRow.state :: KitState` is replaced by+ `StatusRow.conditions :: [KitCondition]` (sorted; empty means up to date),+ `renderState` by `conditionLabel` and `renderConditions`, and `classify`+ returns `[KitCondition]`. `KitUpToDate`, `KitDirty` and `KitDirtyOutdated`+ are gone; match on the list instead. __Breaking__.++- `baikai-kit`: `KitInstall` takes `Maybe Text` (`Nothing` asks the chooser),+ `kitCommandParser` takes the `KitConfig` (migration: `kitCommandParser`+ becomes `kitCommandParser myKitConfig`), `KitConfig` gains the `chooseItem`+ field (set by `kitConfig`), and `KitError` gains `KitItemNameRequired`.+ __Breaking__.++- `baikai-kit`: `KitList`, `KitStatus` and `KitUpdate` gain a trailing+ `OutputFormat` field (`HumanOutput` for the previous behaviour).+ __Breaking__.++## [baikai-effectful 0.4.0.2] - 2026-09-15++### Changed (dependencies)++- Requires `effectful-core ^>=2.7` (was `^>=2.6`). No API change: none of the+ 2.7 breaking APIs (`LocalEnv`'s second type parameter, `SharedSuffix`,+ `KnownEffects`, the ticked strict modules) are used.++## [baikai 0.7.0.0] - 2026-09-08++### Added++- `BaikaiError.refusalCategory` preserves an Anthropic refusal's+ provider category. JSON adds `refusal_category`; older errors still decode.+ Evidence schema 2.5 records the addition without changing digest inputs.+ __Breaking__ to construct a `BaikaiError` from its full field list.++- `Speed`, `Options.speed`, catalog-owned fast rates and+ `computeCostAtSpeed`. Anthropic gates fast mode by model capability, adds the+ beta header and records unsupported drops. Terminal pricing uses observed+ speed, including cache duration; unreported speed is an explicit estimate.+ Older `Model` JSON defaults the new fields safely. __Breaking__: public+ records and sum types gain fields and constructors.++- API usage now records observed service tiers, inference speed and server-tool+ use in optional billing facts covered by evidence schema 2.2. Missing service+ information and uncurated products produce explicit standard-rate estimates.+ `computeCostForService` separates requested and observed service, while+ `computeCostAtRates` prices a resolved rate set once for future speed policies.+ Empty billing facts preserve legacy availability JSON; a CLI-reported zero+ cost retains its reported-total source. __Breaking__: the public vocabulary+ and records gain members.++- Failed trace terminals now retain partial response token counts, cost basis,+ usage availability and USD totals. Synthetic aborts leave unreported billing+ absent; legacy failed trace JSON still decodes. __Breaking__: `TraceEvent`'s+ `CallFailed` gains fields. See `baikai-trace-otel 0.4.0.1` for the export.++- Successful trace terminals and call-log records carry optional cost basis and+ usage availability; call logs also carry cache-write counts. Old JSON decodes+ with absent metadata and empty additive-zero bases stay omitted from traces.+ __Breaking__: `CallFinished` and the call-log record gain fields.++- Optional `Usage.availability` and shared inclusive/exclusive billing+ normalization, in the new `Baikai.Usage.Normalize`. OpenAI Chat/Responses and+ Claude preserve missing cache counters as explicit estimation reasons,+ distinguish reported zeroes, and merge cumulative usage without+ double-counting. Schema 2.2 commits provider availability while preserving+ legacy usage digests. __Breaking__: `Usage` gains a field.++- Optional `Model.pricingPolicy`, exact whole-request context tiers,+ and an explicit cache-duration rate resolver. Generated Astra pricing changes+ above 272000 input tokens; Fable exposes its one-hour write price. `Cost.basis`+ preserves calculation sources and estimation reasons when summed. Evidence+ schema 2.2 serializes the local basis without including local pricing metadata+ in provider commitments. __Breaking__: `Model` and `Cost` gain fields.++- Separate `OpenAIResponses` dispatch and compatibility types, and+ optional provider/model-scoped `ThinkingContent.replayState` with opaque+ diagnostic output and backward-compatible JSON decoding. Evidence schema 2.2+ includes replay state and optional billing facts in commitments while preserving+ legacy encodings when those fields are absent. __Breaking__ for a `case` over+ `Api` that is exhaustive without a wildcard.++- `Baikai.Evidence.ThinkingTranslation` gains `displayText` and+ `ThinkingAdjustment` gains `ThinkingSummaryUnavailable`, so a transport can+ record the thinking display setting it asked for and diagnose a successful+ response whose thinking blocks carry no readable summary. `Baikai.Compat`+ gains `supportsForcedToolChoice`; legacy JSON defaults it to True.+ __Breaking__ for an exhaustive `case` over `ThinkingAdjustment`.++- GPT-6 Astra and Claude Fable 5.1 catalog bindings, with verified+ pricing, token limits, and Anthropic thinking/sampling compatibility.++- Repository `update-models` skill for verifying provider releases and refreshing+ the curated JSON and generated Haskell catalog.++### Fixed++- Preserve OpenAI endpoint capability facts through catalog refreshes.++- Chat and Claude reject provider-scoped reasoning replay they cannot encode.++- Widened the `http-client-tls` bound to admit 0.4 (carried forward from the+ tagged but never-published 0.6.0.1).++## [baikai-claude 0.7.0.0] - 2026-09-08++### Changed++- Refusal messages include the reported category and explanation,+ retaining the original message when neither exists. Classification remains+ non-retryable `ContentFiltered`. Server-side fallbacks remain deliberately+ unsupported, as recorded in ADR 0005.++- Adaptive reasoning requests explicitly ask for summarized+ thinking. Evidence schema 2.4 records the display setting and diagnoses+ successful responses whose thinking blocks contain no readable summary.+ Budget and absent-thinking request shapes, signed empty blocks, redacted+ content and multi-turn replay are preserved.++- Fast mode is gated by the generated model capability: it adds the Anthropic+ beta header for a model that advertises it and records an evidence adjustment+ for one that does not.++### Fixed++- Price Fable cache writes using the TTL in the shaped request,+ including compatibility downgrades. Missing write-duration context is explicit+ in the cost basis.++- Reject forced tool choices locally on Fable 5.1, using the+ generated `supportsForcedToolChoice` capability. Automatic tool rounds retain+ signed empty/visible thinking, redacted blocks and prior-message order.++- Widened the `http-client-tls` bound to admit 0.4 (carried forward from the+ tagged but never-published 0.6.0.1).++### Changed (dependencies)++- Requires `baikai ^>=0.7.0`.++## [baikai-openai 0.7.0.0] - 2026-09-08++### Added++- Explicit `Baikai.Provider.OpenAI.Responses` registration and+ stream/complete provider with stateless reasoning replay, function tool turns,+ structured output and bounded worker cleanup, across the new+ `Baikai.Provider.OpenAI.Responses.{Request,Stream,Assembler}` modules. Astra+ now selects this provider through a per-model catalog override; callers must+ register it explicitly. Cache writes, billing availability and context pricing+ are integrated.++- `Baikai.Provider.OpenAI.Internal.Usage`, the shared usage mapping both the+ Chat Completions and Responses transports read.++### Fixed++- Reject tools locally for models whose Chat Completions endpoint+ disallows them, including GPT-6 Astra. Respect generated effort policies and+ sampling restrictions, with matching translation evidence and strict refusal.++- Validate Responses terminals and enforce the stream contracts.++- Widened the `http-client-tls` bound to admit 0.4 (carried forward from the+ tagged but never-published 0.6.0.1).++### Changed (dependencies)++- Requires `baikai ^>=0.7.0`.++## [baikai-trace-otel 0.4.0.1] - 2026-09-08++### Added++- Successful and failed spans export `baikai.cost.basis` and+ `baikai.usage.availability` as canonically encoded JSON. A failed span now+ also carries the input/output token counts and USD total that+ `baikai 0.7.0.0` retains on `CallFailed`, alongside its error status.++### Changed (dependencies)++- Requires `baikai ^>=0.7.0`, and now depends on `aeson ^>=2.2` to encode the+ two new attributes.++## [baikai-effectful 0.4.0.1] - 2026-09-08++### Changed (dependencies)++- Requires `baikai ^>=0.7.0`. No API change.++## [baikai-kit 0.2.0.1] - 2026-09-08++### Changed (dependencies)++- Requires `baikai ^>=0.7.0`. No API change.++## [baikai-agent 0.2.0.1] - 2026-09-08++### Changed (dependencies)++- Requires `baikai ^>=0.7.0`, `baikai-claude ^>=0.7` and+ `baikai-openai ^>=0.7`. No API change.++## [baikai 0.6.0.1] - 2026-08-30++### Fixed++- widened the `http-client-tls` bound to admit 0.4. The 0.4 API retains the+ manager functions this package uses and belongs to the same TLS 2.x / Crypton+ 1.1 dependency cohort as baikai 0.6; the old `^>=0.3` cap made baikai 0.6+ impossible to solve in applications that require Crypton 1.1.++## [baikai-claude 0.6.0.1] - 2026-08-30++### Fixed++- widened the `http-client-tls` bound to admit 0.4, allowing applications that+ require Crypton 1.1 to solve the dependency set.++## [baikai-openai 0.6.0.1] - 2026-08-30++### Fixed++- widened the `http-client-tls` bound to admit 0.4, allowing applications that+ require Crypton 1.1 to solve the dependency set.++## [baikai 0.6.0.0] - 2026-08-28++### Added++- `baikai`: `Baikai.ThinkingLevel.parseThinkingLevel :: Text -> Maybe+ ThinkingLevel` and `Baikai.Evidence.parseEvidenceStrength :: Text -> Maybe+ EvidenceStrength`, each beside its renderer. Three hand-copied tables — the+ evidence schema's level parser, `baikai-agent`'s KDL `effort` decoder, and its+ `--require-evidence` parser — now read them instead, so a level or strength+ added later cannot be added in one place and missed in three. (REV-2 G.6.)++- `baikai`: `Baikai.Agent.AgentRunResult` exports its selectors (`provider`,+ `exitCode`, `stdout`, `stderr`, `duration`). It exported neither them nor its+ constructor, so a consumer without generic-lens could not read a run's exit+ code at all. (REV-2 G.6.)++- `baikai`: `Baikai.Api.normaliseApi :: Api -> Api`, which collapses a `Custom`+ tag that spells a built-in API onto that constructor. The registry applies it+ to the key it stores and to the tag it is asked for, so a handler registered+ under `Custom "anthropic-messages"` answers a model tagged `AnthropicMessages`+ and the reverse; the two used to be separate entries and dispatch depended on+ which spelling the model happened to carry. Derived `Eq`/`Ord` on `Api` are+ deliberately unchanged: altering them would silently rearrange every+ `Map Api` a consumer holds. (REV-2 G.4.)++- `baikai`: `Baikai.Header`, a new module exporting `HeaderName` with+ `headerName` and `renderHeaderName`. See the `headers` retype under Changed.++- `baikai`: `Baikai.Error.ErrorCategory` gains `ContentFiltered` (wire tag+ `content_filtered`, never retryable) with the smart constructor+ `contentFiltered`. OpenAI's `finish_reason: "content_filter"` and Anthropic's+ `refusal` stop now carry it. Both used to be `OtherError`, so the only way to+ tell a filtered response from any other non-retryable failure was to match on+ the message text. __Breaking__ for a consumer whose `case` over+ `ErrorCategory` is exhaustive without a wildcard. (REV-1 1.7 residual.)++- `baikai` (breaking to construct, not to read): every record that can still+ grow a field is now built from an exported base value and refined by record+ update, and its constructor is no longer exported —+ `Baikai.Provider.Registry.ApiProvider` (`apiProvider` /`apiProviderWith`),+ `Baikai.Evidence.ModelCallEvidence` (`baseEvidence`),+ `Baikai.Evidence.EvidenceRequest` (`evidenceRequest`), `Baikai.Tool.Tool`+ (`mkTool`, with `emptyTool` kept for fixtures),+ `Baikai.Embedding.EmbeddingModel` (`emptyEmbeddingModel`),+ `Baikai.Cost.Log.CallLogConfig` (`callLogConfig`),+ `baikai-trace-otel`'s `OtelSinkOptions` (`defaultOtelSinkOptions`), and+ `baikai-agent`'s `AgentCliOptions` (`agentCliOptions`), `AgentCliRun`+ (`agentCliRun`), `AgentJob` (`agentJob`) and `AgentConfigPaths`+ (`emptyAgentConfigPaths`). Selectors, record update, `OverloadedRecordDot`+ reads and generic-lens labels all keep working; only construction from the+ constructor stops. Adding `describeThinking` to `ApiProvider` in 0.5.0.0 broke+ every third-party registration site, and `strengthCeiling` would have broken+ them again; from this release such an addition is a minor bump. (REV-2 G.1.)++- `baikai`: `Baikai.Provider.apiProvider`, which builds an `ApiProvider` from an+ `Api` tag and a streaming producer, deriving `complete` with+ `streamingComplete`; and `Baikai.Provider.Registry.apiProviderWith`, which+ takes the completer explicitly. Both default `describeThinking` to+ "nothing requested, nothing translated" and `strengthCeiling` to+ `EvidenceRequestedOnly`, matching `declaredStrength (Custom _)`.++- `baikai`: `Baikai.Tool.mkTool` — a tool from its name, description and JSON+ Schema. A tool built from `emptyTool` and sent unchanged reaches the wire with+ `input_schema: null`; `mkTool` has no such shape.++- `baikai`: `Baikai.Agent.AgentOutputFormat` (`TextFormat`, `JsonFormat`) with+ `renderAgentOutputFormat` and `parseAgentOutputFormat`, and+ `AgentRunRequest.outputFormat`, defaulting to `TextFormat`. `baikai-claude`+ renders `--output-format json` and `baikai-openai` renders `--json`, both+ right after the effort flags; `baikai-agent` reads it from+ `jobs.<name>.output-format`. This is the one setting an evidence record needs+ in order to observe a run's session, model and usage, and asking for it used+ to require the `provider-args` channel that an operator ceiling closes by+ default — an operator should not have to open a privileged channel to get a+ record. (REV-2 F.14.)++- `baikai`: `Baikai.Agent.AgentCeiling` gains three fields and the module gains+ the vocabulary they need. `allowedTools :: [Text]` names tool grants the+ operator permits beyond the ones `toolGrantsImpliedBy` (also new) says a+ capability implies on its own; `maxTimeout :: Maybe NominalDiffTime` and+ `maxOutputLimit :: Maybe Int` bound what any job may request, the second+ defaulting to the new `defaultMaxOutputLimit` (67108864, sixty-four+ mebibytes). `Baikai.Agent.ceilingViolations` is `applyAgentCeiling`'s violation+ list on its own, so a caller can concatenate it with violations of its own.+ (REV-2 F.3.)++- `baikai`: `Baikai.Content.toolArgumentsFromText` and+ `Baikai.Content.isCutOffToolCall`. The first is the single rule that turns a+ tool call's accumulated argument text into its `arguments` value — empty text+ is an empty object, non-empty text that does not decode is kept verbatim as a+ `String` — and both provider assemblers and core's stream-recovery path now+ use it, so the second means the same thing at every layer.++- `baikai`: new exposed module `Baikai.Provider.Internal.StreamWorker` — the+ bounded hand-off both HTTP providers now use between their SSE worker thread+ and the consumer draining the stream. `FrameQueue` is a 64-slot `TBQueue` plus+ a closed flag; `forkFrameWorker` closes the queue however the body ends, and+ `withFrameWorker` runs the consumer under `Stream.bracketIO` so the worker is+ killed when the stream stops. The module is exposed like+ `Baikai.Provider.Cli.Internal`, outside the PVP promise. See+ [docs/adr/0010](docs/adr/0010-a-stream-consumer-that-stops-owns-cancelling-the-producer.md).++- `baikai`: every Anthropic model in the generated catalog now carries an+ explicit `CompatAnthropicMessages` record stating the two request-shaping+ facts of its generation: `AnthropicMessagesCompat.thinkingStyle` (which+ extended-thinking wire shape it accepts) and the new+ `AnthropicMessagesCompat.supportsSamplingParameters` (whether it accepts+ `temperature`, `top_p` and `top_k`). Both are sourced from+ `baikai/data/models/anthropic.json`, which the fetcher writes from its+ curated `anthropicInclude` table, and `baikai-gen-models` now refuses an+ `anthropic-messages` entry that reaches it without a `compat` block rather+ than falling back to host auto-detection, which cannot know a generation.+ This is what fixes `claude-sonnet-5`, whose thinking requests were shaped by+ a prefix table that did not know the id. See+ [docs/adr/0009](docs/adr/0009-provider-capability-facts-live-in-the-generated-catalog-record.md).++- `baikai`: two new `Baikai.Evidence.ThinkingAdjustment` constructors,+ `SamplingDroppedUnsupportedModel` and `SamplingDroppedUnsupportedApi`, encoding as+ `{"kind":"sampling_dropped_unsupported_model","fields":["temperature","top_p"]}` and+ `{"kind":"sampling_dropped_unsupported_api","fields":["seed"]}`. They record sampling+ parameters removed because the model generation rejects them, or because the API has no+ such field on any generation. Both carry a `fields` array and no `requested` level, so+ they can appear on a call whose thinking mode is `absent`.++- `baikai`: `Baikai.Evidence.weakensThinking`, which says whether an adjustment weakens the+ thinking the caller asked for. Strict evidence mode filters through it, so a dropped+ sampling parameter is recorded without refusing the call — the documented contract is+ refusing a call that would weaken the requested *thinking level*.++- `baikai`: new exposed module `Baikai.Url` — the one place baikai turns a URL+ into a host name. `parseUrl` yields a `UrlParts` record with the scheme, host,+ port and path, plus flags saying whether userinfo, a query string or a+ fragment were present; it never holds their text, so the value cannot carry a+ secret into a log line. Alongside it: `urlHost`, `hostMatchesSuffix` (moved+ from `Baikai.Compat`, which now re-exports both), `renderEndpoint`,+ `stripApiVersion`, and `baseUrlProblem`, which says why a URL is unusable as a+ `Model.baseUrl` and what to do instead. See+ [docs/adr/0008](docs/adr/0008-one-url-host-parser-and-every-consumer-uses-it.md).++- `baikai`: new exposed module `Baikai.Provider.Transport.Classify` — the one+ rule every HTTP provider uses to classify a transport failure, exporting+ `classifyTransportException` plus the per-type functions it composes. The rule+ is *where* the failure happened, not what type it is: anything that breaks or+ ends the connection after the request went out is `TransientError`, anything+ that says the request or the configuration is wrong is not retryable, and a+ programming error stays `OtherError`. It understands all three shapes+ `http-client` can deliver — an `HttpException` of any constructor, a raw socket+ `IOException`, and a raw or wrapped `TLSException` — because the manager wraps+ the connect phase but not the body reader. Core gains direct `build-depends` on+ `http-types` and `tls`, both already in its install plan. Written for+ third-party `Custom` providers built on `http-client` as much as for baikai's+ own two. See+ [docs/adr/0011](docs/adr/0011-core-owns-transport-failure-classification.md).++- `baikai`: `Baikai.Error.parseHttpDate` and `Baikai.Error.retryAfterSecondsAt`.+ The first parses an HTTP-date in the IMF-fixdate form servers must send plus+ the two obsolete forms a recipient must accept; the second converts a+ `Retry-After` header in either of its forms to seconds against a reference+ instant, clamping a date already in the past to `0`.+ `parseRetryAfterSeconds` keeps its integer-only contract, now a deliberate+ division of labour rather than a limitation.++- `baikai`: new exposed module `Baikai.Http` — `canonicalBaseUrl`,+ `getClientEnvCached` and `cachedClientEnvCount`, the process-global+ `ClientEnv` cache that both HTTP provider packages now share instead of each+ keeping its own. Core gains direct `build-depends` on `servant-client`,+ `http-client` and `http-client-tls`, which were already in its install plan+ through the `openai` SDK.++- `baikai`: `Baikai.Evidence.ThinkingModeNotTranslated`, encoded as+ `"not_translated"`, and `Baikai.Evidence.untranslatedThinking`; and+ `Baikai.Evidence.Build.requestedTranslation`. A path where no adapter ran to+ translate the caller's level now records the level and says the translation is+ unknown, instead of saying nothing was asked. (REV-2 D.2.)++- `baikai`: `Baikai.Evidence.Build.missingEvidenceError`,+ `Baikai.Evidence.Build.strictnessOf` (moved here from `Baikai.Trace`, where it+ was private), `Baikai.Stream.requireEvidenceOnTerminal` and+ `Baikai.Provider.Registry.requireEvidenceOnResponse`. (REV-2 D.3.)++- `baikai`: `Baikai.Evidence.usageEnvelope`, and+ `Baikai.Evidence.Build.endpointIdentityAt`, `prepareEvidenceAt` and+ `minimalEvidenceAt`, which take the base URL the adapter actually resolved.+ The three unsuffixed functions remain and pass the model's own field.+ (REV-2 D.8, D.11.)++- `baikai`: `Baikai.Evidence.deriveStrength`, the single rule that turns an+ observed model, a provider request id and a response id into an+ `EvidenceStrength`. (REV-2 D.10.)++### Changed++- `baikai`: catalog refresh. `claude-opus-5` joins the curated Anthropic include+ set (adaptive thinking, sampling parameters rejected — the facts+ `docs/plans/60-make-anthropic-thinking-style-and-sampling-support-catalog-driven.md`+ said whoever curated it in would have to state), and the `gpt-5.6` family+ picks up its price cut: `gpt-5.6` and `gpt-5.6-sol` to $4.00/$20.00,+ `gpt-5.6-terra` to $2.00/$12.00, `gpt-5.6-luna` to $0.20/$1.20 per Mtok, cache+ rates in step. `Baikai.Models.Generated` gains `anthropic_claude_opus_5` and+ now carries 36 enabled models. No OpenAI id was added: the `gpt-5.6` family is+ still the newest one models.dev reports that speaks+ `openai-chat-completions`.++- `baikai` (breaking): `ResponseFormat`'s `JsonSchema` carries a+ `JsonSchemaFormat` record — `name`, `schema`, `strict`, exported+ selector-only with the base `jsonSchemaFormat name schema` — instead of+ holding the three fields directly. As fields of a sum they were partial+ selectors: `name f` on a `JsonObject` crashed at runtime rather than failing to+ typecheck, which contradicted the module's own documentation.+ `-Wno-partial-fields` is dropped from the module. The JSON encoding is+ deliberately unchanged (`{"tag":"JsonSchema","name":…,"schema":…,"strict":…}`)+ and is now pinned by a test, because `Options` derives `ToJSON` through it and+ at least one consumer keys a cache on the result. (REV-2 G.2.)++- `baikai`: `Baikai.Context.appendToolResult` returns its input context+ unchanged, and runs no dispatcher, when the response is error-shaped. A failed+ call has no assistant turn worth replaying and no tool calls to answer;+ appending its empty message put a turn into the transcript the model never+ took. `runToolLoop` has always stopped on such a response — the documented+ direct round trip in `docs/user/tools.md` reaches `appendToolResult` instead,+ and now behaves the same way. Its Haddock also stops claiming multi-call+ concurrency lives in the dispatcher: the calls are traversed in order.+ (REV-2 G.7.)++- Release metadata (REV-2 G.8): every publishable package now declares+ `tested-with: GHC ==9.12.4` and ships its `CHANGELOG.md` (a symlink to the+ root one, as `baikai` already did) via `extra-doc-files`, so Hackage shows a+ changelog and a tested compiler for all seven. `baikai-claude` and+ `baikai-openai` describe what they actually contain — four surfaces each, not+ "wraps package X" — and `baikai-trace-otel`'s `streamly-core` bound is+ `>=0.3 && <0.5`, matching every other package in the workspace rather than+ excluding the 0.4 series the others accept.++- `baikai` (breaking): `Options.headers` and `Model.headers` are keyed on+ `Baikai.Header.HeaderName` — a newtype over a case-insensitive `CI Text` that+ keeps the original spelling — instead of `Text`. A header name is+ case-insensitive on the wire, so a `Map Text Text` holding both+ `Authorization` and `authorization` sent whichever the assembling fold reached+ last; the map now holds one entry per header and the last write wins, as a+ caller writing two spellings would expect. `HeaderName` has an `IsString`+ instance, so `Map.singleton "x-test" "1"` and `#headers` updates keep+ compiling; the spelling given is what goes out on the wire and into JSON.+ (REV-2 G.5.)++- `baikai` (breaking): `Options.stopSequences` is `[Text]`, where empty means+ "send nothing", instead of `Maybe (Vector Text)` — `Nothing` and `Just []`+ were indistinguishable on the wire and only one of them could be right. Plan+ 43's rule is lists for caller-side configuration and `Vector` for+ provider-bound sequences; this was the one field breaking it. `Options.seed`+ is `Maybe Int` rather than `Maybe Integer`: a seed is a machine integer at+ every provider that accepts one, and it now sits beside+ `timeoutMs :: Maybe Int`. (REV-2 G.5, R14.)++- `baikai` (breaking): `StopReason.Aborted` is removed. Nothing produced it —+ timeouts are `ErrorReason`/`TransientError`, and a consumer abort is recorded+ as evidence `CallAborted` — while `responseError`, `eventsFor` and+ `runToolLoop` all treated it as a *success*, so a value that reached any of+ them would have been silently mishandled. Since 0.6.0.0 a stream consumer that+ stops cancels the producer, so no consumer is left to receive such a terminal+ either. (REV-2 B.6.)++- `baikai`: dispatching a model whose `api` is still `emptyModel`'s+ `Custom ""` says so — `No provider registered for API: <blank Custom tag —+ emptyModel.api was never set>` — where the message used to end after the+ colon. `emptyModel`'s Haddock says the same thing. (REV-2 G.4.)++- `baikai`: `withTrace` and `withTraceStream` wait at most one second for the+ trace sink after writing the shutdown sentinel. On expiry the worker is+ abandoned — not killed, which would abort the sink's fold mid-step and lose+ its end-of-stream action — the call proceeds, and one stderr line reports+ `the trace sink did not confirm delivery within 1000 ms; its worker was+ abandoned, and events already queued may still be delivered later`. A sink+ that blocked forever used to hold the call forever and swallow the first+ attempt to cancel it. A caller under `EvidenceRequired` whose sink did not+ confirm delivery gets a failed call, through the same path a throwing sink+ takes; `Baikai.Evidence.Build.sinkFailureError` now says "its record was not+ confirmed written" rather than "not written", which is the honest claim for+ an abandoned worker whose events are still queued. The synthetic terminal a+ consumer's abort produces is delivered from a garbage-collection hook and is+ not guaranteed before process exit; that was always true and is now stated in+ `docs/user/model-call-evidence.md`, `docs/capabilities/call-tracing.md` and+ the `Baikai.Trace` module documentation, with the pattern for callers who need+ the record. See+ [docs/adr/0015](docs/adr/0015-trace-cleanup-is-bounded-and-abort-cleanup-is-gc-eventual.md).+ (REV-2 D.5, Theme 7.3.)++- `baikai`: `Baikai.Trace.Sink.multiSink` runs each member on its own drain+ thread behind its own unbounded channel, instead of folding `Fold.tee` across+ the list. `Fold.tee` runs one member then the other and lets either's+ exception escape, so a single throwing member stopped delivery to every+ sibling for the rest of the call and skipped their end-of-stream actions — an+ OpenTelemetry span paired with an unwritable file sink was opened and never+ ended, and nothing was exported. The step never blocks; the final action sends+ every member the sentinel, waits for every member, and reports one aggregate+ failure naming each failed member by zero-based index+ (`1 of 2 member sinks failed: member 0: …`). (REV-2 D.6.)++- `baikai`: `AgentSafety.allowedTools` is documented as the __grant__ it is.+ On Claude Code it renders `--allowedTools`, whose help reads "list of tool+ names to allow": it pre-approves tools the permission mode would otherwise+ raise a request for, and in an unattended run a request nobody answers is+ denied. The old Haddock called it "optional narrowing of the provider's tool+ set", which was the opposite, and `applyAgentCeiling` never looked at it. It+ is now bounded: a grant passes when the maximum capability implies it+ (`read-only` implies `Read`, `Glob`, `Grep`, `NotebookRead`, `TodoWrite`;+ `edit-workspace` adds `Edit`, `MultiEdit`, `Write`, `NotebookEdit`;+ `full-access` implies every grant) or when the operator named it in+ `policy.allowed-tools`. Matching is exact, so `Bash(git *)` is not `Bash`.+ A repository job that grants itself `Bash` under `edit-workspace` — which+ passed unexamined before — is now refused with exit 77 before any process is+ created. (REV-2 F.3.)++- `baikai` (breaking): `Baikai.Agent.CeilingViolation` gains five constructors:+ `ToolGrantForbidden`, `TimeoutExceeded`, `OutputLimitExceeded`,+ `RepositoryScopeForbidden` and `WorkingDirOutsideRepository`. A `case` over+ the type that was exhaustive is no longer.++- `baikai` (behaviour): the default ceiling has a finite `maxOutputLimit`, so+ `applyAgentCeiling defaultAgentCeiling` now refuses a request whose+ `outputLimit` is `Nothing` — capture without bound is exactly what the+ maximum exists to refuse. Jobs resolved through `baikai-agent` are unaffected:+ that layer's own default supplies a finite limit, and only an explicit+ `output-limit "unlimited"` reaches the ceiling as `Nothing`.++- `baikai`: a tool call cut off by the output cap is no longer executed.+ `runToolLoop` stops with the response and its tool calls intact when any call+ is cut off, and `appendToolResult` appends a `ToolResultMessage` with+ `isError = True` explaining why instead of calling the dispatcher. Previously+ both assemblers replaced truncated arguments with `{}` and a tool loop+ happily ran the call with no arguments at all. (REV-2 B.2.)++- `baikai`: `Baikai.Model.anthropicMessagesCompatFor` no longer overlays a+ thinking style guessed from the model id onto a model whose `compat` is+ `CompatNone`. `CompatNone` now means host auto-detection alone — the budget+ thinking shape, sampling parameters supported. Every catalog model carries an+ explicit record, so this changes nothing for them; a **hand-rolled** model+ naming an adaptive-era id (`claude-sonnet-5`, `claude-opus-4-7`,+ `claude-opus-4-8`, `claude-fable-5`) must now carry+ `CompatAnthropicMessages (defaultAnthropicMessagesCompat {thinkingStyle = AnthropicThinkingAdaptive, supportsSamplingParameters = False})`+ or start from the catalog value.++- `baikai`: `Baikai.Evidence.evidenceSchemaVersion` is now+ `baikai.model-call-evidence/1.1`. A minor bump: the two sampling adjustment kinds are a+ compatible addition, and no previously recorded digest changes.++- `baikai`: HTTP 413 classifies as `ContextOverflow` rather than `OtherError`,+ from the status alone and whatever the body says. 413 *is* the size-limit+ status and the caller's remedy — shrink the input — is the same either way;+ making the category depend on body wording would recreate for 413 the+ inconsistency this release fixes for connection resets. (REV-2 A.7.)++- `baikai`, `baikai-claude`, `baikai-openai`: an HTTP-date `Retry-After` is+ converted to seconds instead of ignored. Both transports use the response's own+ `Date` header as the reference instant, falling back to the local clock, so a+ CDN-fronted `429` — the common case for a date-valued `Retry-After` — now+ carries a hint rather than leaving the caller to guess. (REV-2 A.9.)++- `baikai`: **breaking.** `Baikai.Embedding.EmbeddingModel.apiKey` is now+ `Maybe ApiKeySource` rather than `ApiKeySource`. `Nothing` means the+ conventional environment variable for the model's host, from+ `defaultApiKeyEnvForBaseUrl` — the same table the chat providers use — and a+ host that table does not know refuses with an `AuthError` naming+ `EmbeddingModel.apiKey`. Migration: `apiKey = source` becomes+ `apiKey = Just source`. `EmbeddingModel` also derives `Eq` and `Generic`, so+ the `#field .~ value` idiom works on it as it does on every other record.+ (REV-2 E.3.)++- `baikai`: **breaking.** `AgentRunFailure`'s `RunTimedOut` constructor now+ carries a new record `AgentTimedOut` — the configured `limit` plus the+ `stdout` and `stderr` a timed-out run drained before its process group was+ killed — instead of a bare `NominalDiffTime`. A caller matching+ `RunTimedOut limit` becomes `RunTimedOut timedOut` and reads `timedOut ^.+ #limit`; `renderAgentRunFailure` is unchanged in what it says. The bytes were+ always there, drained from the moment the child was spawned, and were simply+ dropped on the timeout path — which is the run an operator most wants an+ account of, because the tool started, may have consumed tokens, and may+ already have changed the working tree.++- `baikai`: under `EvidenceRequired`, a successful terminal that carries no+ evidence record fails the call with `missingEvidenceError` rather than+ returning a silent success with zero `call_evidence` lines. Strict mode+ guaranteed that a record which was built and then lost fails the call; it did+ not guarantee that one was built. The rule is applied at both dispatch points,+ so `completeRequest` with no sink gets the same guarantee as a streaming call;+ a failed call keeps the provider's own error, and best effort is unchanged.+ See `docs/adr/0014-strict-evidence-means-a-record-exists.md`. (REV-2 D.3.)++- `baikai`: a caller's thinking level is recorded on every evidence path — the+ consumer abort, an unregistered provider, a `complete` handler that threw, and+ each provider's `immediateError`. The abort path asks the registered adapter's+ own `describeThinking`; the others record `not_translated`. All four used to+ record the caller's request as `absent`, which+ `docs/adr/0002-requested-translated-observed-are-never-collapsed.md` forbids.+ (REV-2 D.2.)++- **`baikai.model-call-evidence/2.0`.** Two digests cover different bytes, so a+ verifier must now select its rules by `schema_version`. `response_commitment`+ covers the provider-reported token counts and never baikai's computed cost:+ the cost comes from the caller's catalog rates rather than from the response,+ so the digest used to change whenever a price was edited and a verifier+ holding only the response could not recompute it. `request_configuration`+ summarises `output_config` and `response_format` as it already summarised+ `tools`, because a structured-output JSON schema carries author-written+ `description` strings and is content wherever it appears — the same schema was+ stripped from `tools[].input_schema` and survived verbatim through the other+ two keys. `thinking.mode` may also now be `"not_translated"`, which is a+ compatible addition. (REV-2 D.7, D.11.)++- **Breaking.** `baikai`: `Baikai.Provider.Registry.ApiProvider` gains a fifth+ field, `strengthCeiling :: EvidenceStrength`, and+ `Baikai.Evidence.Build.checkEvidenceRequirements` takes that ceiling where it+ took an `Api`. The gate compared against `declaredStrength`, a table keyed by+ the API tag, which necessarily answered `EvidenceRequestedOnly` for every+ `Custom` transport — so a gateway that genuinely observes a model could never+ satisfy a strict caller who required that it did. Only a provider knows what+ its evidence reaches. `EvidenceRequestedOnly` reproduces the old behaviour for+ any custom provider; the four built-in providers fill the field from+ `declaredStrength`, which is unchanged in value and still used by the+ unattended-agent surface. (REV-2 D.10, G.1.)++- `baikai`, `baikai-claude`, `baikai-openai`: one strength derivation replaces+ three. An observed **response id** now counts as correlation alongside a+ captured request-id header, so a host that names its model and its response id+ on every chunk but sends no header reaches `model_observed` instead of+ `requested_only` — which had put it *below* a host that sent only a header and+ named nothing. `anthropicStrength` and `openaiStrength` are removed;+ `Baikai.Provider.Cli.Internal.subprocessStrength` keeps its signature and+ delegates. (REV-2 D.10.)++### Removed++- `baikai` **0.6.0.0** (breaking): the sixteen `_Type` base-value aliases deprecated in+ 0.3.0.0 — `_Options`, `_Context`, `_Model`, `_ModelCost`, `_Response`,+ `_Usage`, `_Cost`, `_CostBreakdown`, `_Tool`, `_TextContent`,+ `_ThinkingContent`, `_ToolCall`, `_ImageContent`, `_EmbeddingModel`,+ `_InteractiveLaunchRequest` and `_InteractiveLaunchResult`. Each has an+ `empty…` or `zero…` replacement of the same value, named in the pragma that+ has been on it since 0.3.0.0. The 0.3.0.0 entry said they remained "for this+ release"; 0.4.0.0 and 0.5.0.0 shipped without removing them because no entry+ named a version.+ `docs/adr/0016-deprecated-names-are-removed-at-the-next-major.md` now fixes+ the rule: a name deprecated in `A.B.0.0` is removed in `A.(B+1).0.0`, and+ every pragma says so. (REV-2 G.3.)++- `baikai` **0.6.0.0** (breaking): `Baikai.Trace.newEventId`. It has delegated to+ `Baikai.Evidence.newCallId` since 0.5.0.0; call that. (REV-2 G.3.)++- `baikai` **0.6.0.0** (breaking): `Baikai.Compat.defaultAnthropicThinkingStyle`, deprecated+ earlier in this cycle. Nothing in baikai consults it — the thinking style of a+ first-party Anthropic model is a field of its generated catalog record+ (`Baikai.Models.Generated`); start from that value, or set+ `CompatAnthropicMessages` explicitly.++- `baikai` (breaking): `AgentRunRequest.envPassthrough` is renamed `envRequires`.+ The field is a list of variables the job declares it requires, checked as a+ precondition; it has never passed anything through, and the KDL key has said+ `env-requires` since the setting existed.++- `baikai` (breaking): `AgentRunFailure.OutputMalformed`, and with it+ `baikai-agent`'s exit code 70 and its `internalExitCode` export. Nothing ever+ constructed the constructor, and giving it a producer would have been wrong:+ the runner treats the tool's output as best-effort observation and its+ deliverable is the changed working tree, so a run that edited files correctly+ and then printed an unparseable final line would have been reported as a+ failure with its exit code and output discarded. A record's `strength` and+ `unobserved` fields already say when output could not be read. (REV-2 F.13.)++### Fixed++- `baikai`: the terminal event and its evidence record are pushed to the trace+ sink exactly once under asynchronous exceptions. The terminal path pushed the+ evidence record, pushed the terminal event and only then set the+ already-sent flag; an exception delivered between the last two made the+ stream finaliser read the flag as unset and push a second `CallEvidence` and+ an `aborted` `CallFailed` after the real `CallFinished`, so a sink saw two+ records and two contradictory terminals for one call. All three writes now+ run inside one `uninterruptibleMask_` with the flag first. (REV-2 D.4.)++- `baikai`: `Baikai.Cost.Log.closeCallLog` is idempotent. The first caller+ claims the handle and waits for the worker; a second returns at once instead+ of blocking forever on an `MVar` the worker had already emptied — a shape+ `withCallLog` makes easy to reach, since its bracket closes a handle the body+ may also have closed. An `appendEntry` after the close enqueues nothing.++- `baikai`: `reassembleResponse` is total under duplicated, late and+ timestamp-less input. The first `EventStart` wins the skeleton and+ `responseId` merges with `<|>`, so a later `Nothing` cannot erase an id an+ earlier event supplied; events after the first terminal are ignored, so a+ producer that keeps talking cannot rewrite the answer; and `latencyMs` falls+ back to the reassembler's own wall clock when neither the skeleton nor the+ terminal carries a provider timestamp, instead of reporting a zero that reads+ as "instant". (REV-2 B.7.)++- `baikai`: an `EmbeddingModel` pointed at a non-OpenAI host no longer sends+ `OPENAI_API_KEY` to it. The default key source was that variable whatever the+ base URL said, so pointing the client at DeepSeek handed DeepSeek an OpenAI+ credential. It now resolves per host, and refuses an unknown one. New+ `resolveEmbeddingKey` and `embeddingClientEnv` expose both decisions without+ making a request. (REV-2 E.3.)++- `baikai`: `Baikai.Embedding.embed` no longer allocates a TLS manager per call.+ It used the `openai` SDK's own `getClientEnv`, which builds a fresh manager+ every time; it now takes one from `Baikai.Http`'s process-global cache, the+ same one the chat providers use, so an embedding call and a chat call to one+ host share a connection pool.++- `baikai`: **a credential in a header is no longer printed.** `Options.headers`+ and `Model.headers` went through derived `Show` and `ToJSON` instances that+ rendered every value verbatim — while `Baikai.Options`' own documentation+ invites callers to put a gateway's `Authorization` header there and the+ getting-started guide tells them to `print resp`, which renders the embedded+ `Model`. Both types now have hand-written instances that render exactly what+ the derived ones did, except that the value of a header whose name looks+ credential-carrying (`authorization`, `api-key`, `apikey`, `token`, `secret`,+ `cookie`, `password`, or any name ending in `-key`, case-insensitively) prints+ as `<redacted>`. `Baikai.Auth` exports the three pieces — `redactedMarker`,+ `isCredentialHeader`, `redactHeaderValues` — so a caller can apply the same+ rule to its own logging. Only the rendering changes: the field is untouched,+ `Eq` is untouched, and the header is still sent as written. A JSON round trip+ of a `Model` is deliberately lossy, since a serialised `Model` is exactly the+ thing that should not carry a key. (REV-2 E.2.)++- `baikai`: an API-key environment variable set to the empty string, or to+ nothing but whitespace, now counts as **unset**. `ApiKeyEnv` fails with an+ `AuthError` naming the variable and saying it is not set or is empty;+ `ApiKeyEnvChain` skips it and continues, and reports every name when none+ yields a key. Previously an empty variable resolved to an empty key, which+ short-circuited a chain and produced `Authorization: Bearer ` and a provider+ 401 that said nothing about the cause. A key with real content is still passed+ through untrimmed. (REV-2 E.6.)++- `baikai`: **the host parse no longer lets a base URL choose which key baikai+ sends.** `urlHost` took the text after the *last* `@` anywhere in a URL, so+ `https://proxy.example.com/v1?u=@api.openai.com` named the host+ `api.openai.com`: `defaultApiKeyEnvForBaseUrl` resolved `OPENAI_API_KEY`,+ `autoDetectOpenAICompletions` returned OpenAI's own compatibility record, and+ the bearer token went to `proxy.example.com`. Anyone who could set `baseUrl` —+ a `Model` decoded from JSON, a proxy override — could pick which provider's+ credential to be handed. The same defect broke the benign direction:+ `https://api.openai.com/v1/@x` named the host `x` and resolved no key at all.+ The authority now ends at the first `/`, `?` or `#`, and userinfo is only ever+ the last `@` inside it. (REV-2 A.1 / E.1.)++- `baikai`: `Baikai.Evidence.Build.sanitizeEndpoint` was a second, separately+ written parser that bounded the authority at the first `/` only, so a URL with+ a query and no path recorded the wrong host. It is now `renderEndpoint <$>+ parseUrl`, which also means a recorded endpoint has a lower-cased scheme and+ host; the path keeps its case and trailing slash.++- `baikai`: `parseCodexJsonlStream` assembles lines in **linear time**. It+ previously unpacked every chunk into a stream of bytes and appended them one+ at a time with `BS.snoc`, copying the whole accumulator per byte — quadratic+ in line length, so one codex event carrying a two-million-character message+ cost on the order of a trillion byte moves and in practice never finished.+ Lines are now cut out of each chunk with `BS.elemIndex` and `BS.splitAt`, and+ the pieces of a line that spans a chunk boundary are joined once. Behaviour is+ unchanged: a non-JSON line is still skipped, and a last line without a+ trailing newline is still parsed.++- `baikai`: a Codex custom agent's instructions body renders as a TOML+ **literal** multi-line string (`'''`), which interprets nothing, instead of a+ basic one (`"""`), which interprets backslash escapes. As a basic string an+ instruction as ordinary as "match `\d+`" made Codex refuse to load the file;+ `tomllib` rejects the old output with `Unescaped '\' in a string`. A body a+ literal string cannot hold — one containing three apostrophes, a bare carriage+ return, or a control character other than tab and newline — falls back to a+ fully escaped basic string. `tomlString`, which renders `name` and+ `description`, now escapes every control character as TOML 1.0 requires+ instead of only the five it happened to name.++- Documentation: `baikai`'s Haddock no longer describes behaviour the code left+ behind. The trace event's token counts are `Maybe` because a non-assistant+ terminal has no usage, not because the CLI providers report nothing — since+ 0.5.0.0 both carry what the tool reported. `EventStart`'s `partial` is a+ message skeleton with empty content, zero usage and no stop reason; the api,+ provider and model id live on the `Response`. A lifted stream's `EventStart`+ carries the final usage and stop reason already filled in, because the+ response is complete before the stream begins. `Baikai.CacheRetention` no+ longer mentions an OpenAI Responses 24-hour bucket no code emits. System+ prompts are documented as living on `Context.systemPrompt` rather than on a+ `Baikai.Request` module that no longer exists, `emptyModel`'s `compat` is+ described as auto-detection rather than a placeholder, tool dispatch says+ calls run one at a time in order, and every reference to a plan number is+ gone. (REV-2 H.4.)++## [baikai-claude 0.6.0.0] - 2026-08-28++### Added++- `baikai-claude`: `Baikai.Provider.Claude.Internal.Request` exports `planRequest`,+ `SamplingPlan`, `uncappedMaxTokensFloor` and `normalizeToolCallId` as test seams.+ `planThinking` and `describeThinkingFor` are now projections of `planRequest`, so the+ strict gate, the request builder and the evidence record read one answer.++### Changed++- `baikai-claude`, `baikai-openai` (breaking): each provider's streaming+ machinery moved from `Baikai.Provider.<P>.Api` to+ `Baikai.Provider.<P>.Internal.Stream` — the `SseDriver` seam, `liveSseDriver`,+ `<p>StreamWith`, `Assembler`, `emptyAssembler`, `translate`, and on the OpenAI+ side `RawChunk`, `RawToolDelta`, `parseChunk`, `parseFrame`, `TagScanState`,+ `scanThinkTags`, `closeOpenStream`, `RawUsage`, `parseUsage` and+ `rawUsageToUsage`. `Api` now exports exactly `register`, the provider value+ and the live stream function. The `.Internal` module is exposed for the test+ suites and sibling packages and, like every `.Internal` module, may change in+ any release without a major bump — so changing the assembler stops being a+ documented break. `Shape`, `Sse` and `Transport` keep their names and gain the+ same no-guarantees header. `_TagScanState` is renamed `emptyTagScanState`.+ (REV-2 G.1.)++- `baikai-claude`, `baikai-openai`: a consumer that stops reading now stops the+ provider. Both packages fork their SSE worker under `Stream.bracketIO` and+ hand frames through the bounded `FrameQueue` above instead of an unbounded+ `Chan`. A consumer that cancels — `Ctrl-C`, `System.Timeout.timeout`,+ `cancel` — releases the HTTP connection immediately; a consumer that abandons+ the stream (`Stream.take 3`) stops the socket read within 64 further frames+ and releases the connection at the next major garbage collection. Previously+ the worker read the entire generation into memory for a consumer that would+ never look at it, and the provider billed all of it. The three cleanup+ strengths are stated in+ [docs/adr/0010](docs/adr/0010-a-stream-consumer-that-stops-owns-cancelling-the-producer.md)+ and in caller terms in `docs/user/streaming.md`.++- `baikai-claude`: `anthropic_claude_sonnet_4_6` now sends the adaptive+ thinking shape rather than `budget_tokens`. The budget shape is deprecated+ for that generation; baikai sends the shape Anthropic documents as current.++- `baikai-claude`, `baikai-openai`: **behaviour change.** `Options.timeoutMs` of+ `Just n` with `n <= 0` is refused as `InvalidRequest` before the action runs, so+ no connection is opened. `System.Timeout.timeout` returns immediately at zero+ and runs unbounded below it, and the previous `max 0` clamp made both spellings+ fail instantly as a *retryable* `TransientError` — a classification a caller's+ retry loop re-issues forever for what is a configuration mistake. `Nothing`+ remains the only spelling of "no bound". (REV-2 A.10.)++- `baikai-claude`, `baikai-openai`: an evidence record's `endpoint` names the+ host the call actually went to. Both adapters substitute a vendor default for+ an empty `Model.baseUrl` inside `prepareCall`, so a call with a perfectly+ definite destination recorded `endpoint: null`. Where no adapter ran, `null`+ remains the truthful answer. (REV-2 D.8.)++- `baikai-claude`: the `claude` dependency moves from `^>=1.4` to `^>=1.5`.+ 1.5.0 adds a `Pause_Turn` constructor to `Claude.V1.Messages.StopReason`, and+ `mapStopReason` matches that type with no wildcard under+ `-Werror=incomplete-patterns`, so the bump forced a decision. A paused turn+ maps to `Stop`: Anthropic suspends the turn mid-flight for a long-running+ server-side tool and expects the caller to send the message back to continue+ it, so nothing failed, and `Baikai.StopReason` has no constructor that says+ "resume me". Widening that public sum is a breaking change for every consumer+ who matches on it exhaustively, and it is not this bump's to make. The general+ rule is+ [ADR 0018](docs/adr/0018-a-provider-stop-reason-with-no-baikai-equivalent-maps-to-the-nearest-truthful-one.md):+ a provider stop reason with no baikai equivalent maps to the constructor that+ is truthful about whether the call failed, and the sum widens only when baikai+ would behave differently for it.++- `baikai-claude`: `Messages.StreamUsage` lost its `Generic` instance in `claude`+ 1.5.0, so the `message_delta` usage is read through `OverloadedRecordDot`+ rather than a generic-lens label. `Messages.max_tokens` and+ `Messages.output_config` became ambiguous selectors — `Messages.Fallback`+ carries both names — so the provider's tests read them through `^. #max_tokens`+ and `^. #output_config` instead.++### Removed++- `baikai-claude`, `baikai-openai` **0.6.0.0** (breaking): the eight registration shims —+ `registerWith`, `registerWithRegistry` and `registerWithRegistryAndConfig` in+ both `Cli` modules, and `registerWithRegistry` in both `Api` modules. Register+ the exported provider value instead:+ `registerApiProvider (claudeCliProvider cfg)`,+ `registerApiProviderWith reg (codexCliProvider cfg)`,+ `registerApiProviderWith reg claudeMessagesProvider`. The batch-mode note that+ had accumulated on `registerWith` — why `complete` stays on the direct path+ rather than going through `streamingComplete` — moves to the provider value it+ describes. (REV-2 G.3.)++- `baikai-claude`, `baikai-openai`: `responseToError` and `classifyErrorText`+ (and its private `classifySdkHttpText` half) from both+ `.Internal.ErrorClass` modules. Neither package runs a `servant-client` client+ on the chat path any more, so the `ClientError` branch was unreachable, and the+ text classifiers parsed a string shape the local SSE transports stopped+ producing in July. The phrase table `classifyErrorText` held survives as the+ message fallback inside `classifyErrorFrame`, pinned through the entry point the+ runtime actually uses. Both modules are documented as outside the PVP-stable+ surface, so this is not a major bump; version bumps are recorded once, later.++- **Breaking.** `baikai-claude`: `Baikai.Provider.Claude.Api.anthropicStrength`+ and `baikai-openai`: `Baikai.Provider.OpenAI.Api.openaiStrength`, both replaced+ by `Baikai.Evidence.deriveStrength`.++### Fixed++- `baikai-claude`, `baikai-openai`: a failure that lands while the response body+ is streaming is classified as the transient failure it is. A connection reset,+ a server closing the socket mid-chunk, a body shorter than its declared length+ and a TLS session torn down after the handshake all now terminate the stream+ with `TransientError` and `isRetryable = True`, carrying whatever text had+ already been drained. Every one of them used to be `OtherError` with+ `isRetryable = False`, while the identical failure at connect time was+ transient — because `http-client` wraps the connect phase with the manager's+ exception wrapper and the body reader with nothing that converts a socket+ `IOException` or a `TLSException`, so those reached the worker raw and missed+ the `HttpException` branch entirely. (REV-2 A.2.)++- `baikai-claude`, `baikai-openai`: a transport failure mid-stream now closes+ the blocks that were open when it arrived, on both providers, so a consumer+ reading raw events and a consumer reassembling them see the same partial+ output. Both providers built their terminal from the closed blocks alone and+ silently dropped open text, thinking and tool arguments. On the Claude side+ this covers `translate (Left …)`, the in-band `error` frame, and the+ unexpected end of stream. (REV-2 B.3.)++- `baikai-claude`: an SSE frame whose event `type` — or whose+ `content_block_delta` `delta.type` — the SDK has no constructor for is now+ skipped instead of ending the stream with a decode error. The SDK decodes both+ with no unknown-tag fallback, so a new frame type from Anthropic used to be a+ terminal fault. A frame of a *known* type that still fails to decode remains+ one. `Baikai.Provider.Claude.Sse` exports the new `decodeFrame`. (REV-2 B.5.)++- `baikai-claude`, `baikai-openai`: an empty `data:` heartbeat is ignored, and+ on the OpenAI side `[DONE]` is compared after trailing whitespace is trimmed,+ so `data: [DONE] ` and `data: [DONE]\r` end the stream rather than failing to+ decode. (REV-2 A.8.)++- `baikai-claude`: every failing stream now begins with `EventStart`. The+ producer pre-seeds the start event before the first wire read, exactly as the+ OpenAI producer already did, and `message_start` updates the assembler without+ emitting a second one. Previously a 401, a rate limit, an in-band `error`+ frame or an EOF arriving before `message_start` produced a lone `EventError`,+ breaking the protocol `Baikai.Stream.Event` documents. `StartPayload.responseId`+ is consequently `Nothing` on both HTTP providers; the provider's message id+ rides `TerminalPayload.responseId`, which `reassembleResponse` already prefers.+ (REV-2 A.4, REV-1 Theme 1.1.)++- `baikai-claude`, `baikai-openai`: an asynchronous exception delivered to the+ stream worker can no longer strand its consumer. End-of-frames is a flag set+ by the worker fork's own `finally` rather than a sentinel value pushed onto+ the channel, so a worker that dies without running its normal exit path still+ ends the stream in an `EventError`. Previously the consumer blocked until the+ runtime's deadlock detector noticed.++- `baikai-smoke`: two keyed cases against `claude-sonnet-5` — one asking for+ thinking (which is a 400 before this release) and one setting `temperature` — plus+ `deepseek-chat` and `openrouter/openai/gpt-4o-mini` in `apiCases`, so the tool and+ structured-output smokes run against a compatible host that is not OpenAI.+ `CompatSmoke` now asserts DeepSeek honoured the output cap rather than only that it+ answered, and `CacheSmoke` asserts the cached token classes cost something.++- `baikai-claude`: a thinking request on `claude-sonnet-5` no longer 400s. It sends+ `"thinking":{"type":"adaptive"}` and no `budget_tokens`, because the shape is read off+ the model's catalog record rather than guessed from its id. (REV-2 C.1.)++- `baikai-claude`: `temperature` and `top_p` are no longer sent to a model generation that+ rejects them with a 400. They are omitted and the omission is recorded as+ `sampling_dropped_unsupported_model` in the call's evidence. `seed`, `frequencyPenalty`+ and `presencePenalty`, which the Anthropic Messages API has no field for on any+ generation, are recorded as `sampling_dropped_unsupported_api`. (REV-2 C.1, C.5.)++- `baikai-claude`: a model whose `maxOutputTokens` is `0` no longer sends+ `"max_tokens":0`, which Anthropic rejects — and, with thinking set, no longer had its+ whole thinking plan discarded for not fitting inside a ceiling of zero. It sends+ `uncappedMaxTokensFloor` (1024, the SDK's own default) instead. An explicit+ `maxTokens = Just 0` is still forwarded as written. (REV-2 C.2.)++- `baikai-claude`: replay no longer sends an empty text block or an empty `content` array,+ both of which Anthropic rejects. An empty text block is dropped; an assistant turn left+ with nothing is dropped whole (it is baikai's own artifact — a block that closed with no+ deltas, or only unsigned thinking, which replay already omits); a user turn left with+ nothing is refused locally with a message naming the turn. (REV-2 C.3.)++- `baikai-claude`: tool-call ids that differ only in characters the alphabet forbids, or+ only past character 64, no longer normalise onto the same id and misroute a tool result.+ A conforming id passes through unchanged — every id Anthropic and OpenAI actually mint+ does — and any other is truncated to 51 characters and suffixed with twelve hex+ characters of its SHA-256. Two `tool_use` blocks in one turn that still collide are+ refused rather than sent. (REV-2 C.7.)++- Documentation: `baikai-claude`'s and `baikai-openai`'s Haddock point at the+ functions that exist. `Baikai.Compat` named+ `Baikai.Provider.OpenAI.Api.mkOpenAIResponseFormat`,+ `…Api.applyThinkingFormat` and `…Api.translateTextLikeDelta`; the first two+ moved to `…Internal.Request` and the third is+ `…Internal.Stream.scanThinkTags`. `ThinkingFormat`'s note said the six+ non-native shapes all clamp through `compatibleEffort`; three do, Z.ai and+ Qwen send a bare toggle, and `ThinkingFormatNone` drops the control.+ `immediateError` carried two `-- |` headers where one was intended.+ (REV-2 H.4.)++- `baikai-claude`: an Anthropic call reports its thinking tokens. `Usage.reasoningTokens`+ was hard-coded to `Nothing` on this provider because `claude` 1.4.0's+ `Messages.Usage` had no breakdown to read; 1.5.0 adds+ `output_tokens_details.thinking_tokens`, and both `message_start` and+ `message_delta` now fill the field from it. `reasoningTokens` is an+ informational subset of `outputTokens`, so no total and no cost moves.++- `baikai-claude`: the prompt-side token counts survive a server-side tool run.+ The final `message_delta` used to contribute only `output_tokens`, and+ `inputTokens`, `cacheReadTokens` and `cacheWriteTokens` kept whatever+ `message_start` had reported — which is wrong for a call whose prompt grew+ mid-stream. `claude` 1.5.0 exposes those three on `Messages.StreamUsage`, and+ each is now taken when present. An absent field still keeps the+ `message_start` figure rather than zeroing it, so a model that sends only+ `output_tokens` is accounted for exactly as before.++## [baikai-openai 0.6.0.0] - 2026-08-28++### Added++- `baikai-openai`: `Baikai.Provider.OpenAI.Internal.ErrorClass.classifyErrorFrame`+ and `Baikai.Provider.OpenAI.Api.parseFrame`, which sort a decoded SSE payload+ into a classified in-band error or a completion chunk.++### Changed++- `baikai-openai`: **breaking.** `Baikai.Provider.OpenAI.Shape`'s+ `injectThinkingShape`, `describeThinkingShape`, `shapeRequestBody` and+ `streamRequestBody` take a `Bool` after the compat record — whether the model+ advertises reasoning support (`Model.reasoning`). A level on a `reasoning = False`+ model now sends no `reasoning_effort`, `reasoning`, `thinking` or `enable_thinking`+ key on any host, and records `thinking_dropped_unsupported_model` instead. The model+ check runs before the host-format check. This is what stops `gpt-4o-mini` plus a+ level from 400ing. (REV-2 C.4.)++### Fixed++- `baikai-openai`: an in-band `{"error": …}` frame on a `2xx` stream terminates+ the call with the frame's own classification, status and message. Compatible+ hosts (OpenRouter, DeepSeek, Together) report an upstream failure they only+ learned about after committing to a `200` this way, and `parseChunk` never+ looked at `error`. The pre-fix behaviour was worse than a bad category:+ OpenRouter's frame carries `choices[0].finish_reason = "error"`, which mapped+ to `Stop`, so the call ended as `EventDone` with `errorInfo = Nothing` — a+ consumer switching on the terminal saw a *completed* call. A frame with no+ `choices` beside the error ended as+ `OtherError "openai stream ended without finish_reason"`. (REV-2 A.3.)++- `baikai-openai`: reasoning that arrives after visible text closes the open+ text block before opening the thinking block, so at most one of the two is+ open at a time, every `_End` precedes the next `_Start`, and no `contentIndex`+ is revisited after a later one. (REV-2 B.4.)++- `baikai-openai`, `baikai-claude`: **a provider POST no longer follows+ redirects.** `http-client`'s default is to follow up to ten with every header+ intact, so a 3xx would have re-sent the bearer token (or `x-api-key`) to+ whatever host the `Location` header named. `redirectCount` is now zero and the+ 3xx is delivered as the one in-band terminal error carrying its status. Each+ transport's request builder is exported as `buildRequest`, so the method, the+ composed path and the redirect policy are assertable without a connection.+ (REV-2 A.5 / E.4.)++- `baikai-openai`, `baikai-claude`, `baikai`: **the base-URL convention is+ stated and enforced.** `Model.baseUrl` and `EmbeddingModel.baseUrl` are the+ API *root* — the host, or the prefix a host mounts the API under — because+ baikai appends `/v1/chat/completions`, `/v1/messages` or `/v1/embeddings`+ itself. A trailing `/v1` is accepted and removed rather than doubled, so+ `https://api.deepseek.com/v1` now requests `/v1/chat/completions` instead of+ `/v1/v1/chat/completions`. A base URL with no scheme, a scheme other than+ `http`/`https`, credentials, a query string, a fragment, or a path that is+ already an endpoint is refused as an `InvalidRequest` naming the problem —+ and refused *before* a key is read, so an unusable base URL never causes a+ credential to be looked up. The message renders the URL without its userinfo+ or query, so it is safe to log. `docs/user/models-and-providers.md` gains a+ **Base URLs** section stating all of it. (REV-2 A.6.)++- `baikai-openai`, `baikai-claude`: the `ClientEnv` cache was duplicated in each+ package and keyed on the raw base-URL text, so `https://h` and `https://h/`+ were two TLS managers and two connection pools to one host. There is now one+ cache, in `Baikai.Http`, keyed on the canonical rendering of the parsed base+ URL. `Transport.getClientEnvCached` and `Transport.cachedClientEnvCount` are+ re-exports of the core functions and keep their signatures.++- `baikai-openai`: the Codex interactive launcher now **refuses the two approval+ policies the installed CLI rejects**. `codex --help` at `codex-cli 0.149.1`+ lists exactly `on-request` and `never` for `--ask-for-approval`;+ `CodexApprovalUntrusted` and `CodexApprovalOnFailure` are older spellings the+ CLI answers with `error: invalid value 'untrusted' for+ '--ask-for-approval'`. Rendering them made a launch return `Right` carrying a+ non-zero exit code — a session that ran and failed — instead of the `Left+ SafetyNotExpressible` this module promises for a policy that cannot be+ honoured. They are refused before any process is created, and refused rather+ than quietly mapped onto `on-request`, because substituting a different+ approval policy would change what the caller asked for. The constructors and+ their spellings are unchanged, so code that matches on `CodexApprovalPolicy`+ keeps compiling.++## [baikai-trace-otel 0.4.0.0] - 2026-08-28++### Added++- `baikai-trace-otel`: `OtelSinkOptions` derives `Generic`, so `#spanName`+ resolves on it. No `Eq` or `Show`: `OpenTelemetry.Context.Context` has neither,+ and an instance that ignored `parentContext` would be a lie. (REV-2 G.6.)++- `baikai-trace-otel`: `OtelSinkOptions.parentContext :: Maybe Context`, default+ `Nothing`. When set, every span the sink opens becomes a child of the span in+ that context instead of a root, so a call can be nested under the caller's own+ request span. It is a value fixed when the sink is built rather than an action+ run per call, because the fold runs on baikai's trace worker thread where the+ caller's thread-local context is invisible: capture the context on your own+ thread (`ctx <- getContext`, or `Context.insertSpan mySpan Context.empty`) and+ build the sink for that request. __Breaking for positional construction__ of+ `OtelSinkOptions`; the documented path is a record update on+ `defaultOtelSinkOptions`. (REV-2 D.9.)++### Changed++- `baikai-trace-otel`: the `baikai.evidence.strength` span attribute is rendered+ by `Baikai.Evidence.renderEvidenceStrength`, the function the JSON encoding+ uses, instead of a second spelling local to the sink that could drift from it.++- `baikai-trace-otel`: `gen_ai.response.model` is set only by the evidence+ branch, from the model the provider reported. The terminal branch set it from+ the *requested* id, and since evidence is pushed before the terminal and+ `addAttributes` replaces a key, that both labelled a request as an observation+ on every call without evidence and overwrote the genuinely observed value on+ every call with one. (REV-2 D.1.)++## [baikai-effectful 0.4.0.0] - 2026-08-28++### Changed++- `baikai-effectful` (breaking): the version is a **major** bump although this+ package's own exports are unchanged. Its `baikai` bound moves to `^>=0.6.0`,+ and the `Baikai` effect's three operations are typed in `Model`, `Context`,+ `Options` and `Response` — every one of which baikai 0.6.0.0 changes+ breakingly. A consumer therefore meets a break through this package even+ though nothing in it was renamed, so the number says so rather than making+ `0.3.0.4` look like a safe upgrade.++- `baikai-effectful`: no longer depends on `streamly`. Both stanzas listed it+ while every module imports only `Streamly.Data.Fold` and+ `Streamly.Data.Stream`, which are `streamly-core`. (REV-2 minor.)++## [baikai-kit 0.2.0.0] - 2026-08-28++### Added++- `baikai-kit`: `Baikai.Kit.Error` with the closed `KitError` sum, its+ `Exception` instance and `renderKitError`; `Baikai.Kit.Path.safeSourcePath`,+ which resolves an untrusted relative source below the kit checkout and refuses+ a symbolic link in any component or a canonical path outside the checkout;+ `Baikai.Kit.Manifest.itemSources`/`ItemSources`, the one pure derivation of an+ item's source list, and `supportedManifestVersions`;+ `Baikai.Kit.Sidecar.hashEntries`; `Baikai.Kit.Repo.KitRepo`/`RepoRefresh`;+ `Baikai.Kit.Install.installFrom`, `renderAvailable` and `UpdateReport`;+ `Baikai.Kit.Status.StatusReport`, `UpstreamAvailability` and the now-pure+ `renderStatusTable`; `Baikai.Kit.Command.runKitCommand`. `KitState` gains+ `KitUpstreamRefused`, rendered `refused`. (REV-2 E.5, F.10, F.11.)++- `baikai-kit`: `Baikai.Kit.Install.OverwritePolicy` (`KeepLocalEdits`,+ `OverwriteLocalEdits`), `reinstallPresent` (the network-free half of+ `updateKit`), and `PlannedWrite`/`WriteContent`/`executePlan`/`executePlanWith`+ as a test seam. `SidecarMeta` gains `installedFiles` and `installedHash`,+ which record what this tool wrote for one provider and the hash of exactly+ those bytes; `newSidecarMeta` takes both. `kit update` gains `--force`.+ (REV-2 F.12, Theme 8.2.)++### Changed++- **Breaking.** `baikai-kit`: every library function returns+ `Either KitError a` and prints nothing; only+ `Baikai.Kit.Command.runKit` prints `Error: …` and exits 1. `loadManifest`,+ `loadManifestMaybe`, `installItem`, `listAvailable`, `uninstallItem`,+ `updateKit` and `ensureKitRepo` change shape accordingly, `computeKitHash`+ takes the kit root, a base and relative file names, `kitStatus` returns a+ `StatusReport` instead of printing, and `KitUpdate`'s report is rendered by+ the caller. See `docs/adr/0013-library-code-never-calls-exitfailure.md`. A+ consumer that only calls `runKit` and `kitCommandParser` needs no change; one+ that calls the library directly binds `Right`. (REV-2 F.11.)++- `baikai-kit`: a kit is plain files. Install, the content hash and `kit status`+ resolve every listed source through `safeSourcePath`, so a kit repository that+ commits a symbolic link can no longer have a file read through it and copied+ into a provider directory. `kit status` shows such an item as `refused`.+ (REV-2 E.5 = F.10.)++- `baikai-kit`: a manifest whose `version` is not 1 or 2 is refused with+ `KitManifestVersionUnsupported` instead of being decoded and installed.+ (REV-2 F.12.)++- `baikai-kit`: an agent that lists several `files` installs all of them. The+ first becomes the provider's agent file as before, and each remaining file+ goes into a resource directory named after the agent beside it+ (`<agents dir>/<name>/<file>`), which uninstall removes with the agent. Only+ the first file used to be installed. (REV-2 F.12.)++- `baikai-kit`: `kit update` skips an item whose installed files no longer hash+ to what its sidecar recorded, printing the `--force` invocation that would+ overwrite them; `kit update --force` reinstalls anyway. Sidecars written+ before this release carry no such hash and are updated without the check.+ (REV-2 Theme 8.2.)++### Removed++- **Breaking.** `baikai-kit`: `Baikai.Kit.Path.safeUnder` (exported and unused),+ `Baikai.Kit.Manifest.agentSources` (replaced by `itemSources`) and+ `Baikai.Kit.Install.uninstallOutcomes` (absorbed by `uninstallItem`, which now+ returns the outcomes for the caller to render). The internal `requireSafe` and+ `Baikai.Kit.Status.resolveCacheOrEmpty` are gone with the exits they wrapped.++### Fixed++- `baikai-kit`: `kit status` with no cache and no network prints+ `No kit items installed.` and exits 0. It used to exit 1: the guard around+ `ensureKitRepo` caught `IOException`, which is not what `exitFailure` throws.+ (REV-2 F.11.)++- `baikai-kit`: `Baikai.Kit.Status.upstreamHash` joined the manifest `path`+ without validating it, a second unsanitised join that grew after the July+ hardening pass validated the first. Both now go through `itemSources` and+ `safeSourcePath`. (REV-2 Theme 8.1.)++- `baikai-kit`: an install that fails while renaming files into place now+ restores what was there before, or names the paths it could not restore.+ Phase two was a bare loop of renames, so a failure part-way left earlier+ renames in place while the message said "no changes were made". Temporary+ files are also created with `openTempFile`, so two concurrent installs of one+ item no longer clobber each other's staging file, and a destination that is a+ directory is refused before anything is written. (REV-2 F.12.)++- `baikai-kit`: `Baikai.Kit.Install.stripYamlFrontmatter` normalises line+ endings to LF on every branch. Input without frontmatter, and input whose+ frontmatter is never closed, used to keep their `\r` characters and leak them+ into the Codex agent TOML. (REV-2 Theme 8.7.)++- `baikai-kit`: an `IOException` raised while reinstalling during `kit update`+ is returned as `KitWriteFailed` instead of escaping as an uncaught exception.+ (REV-2 Theme 8.4.)++## [baikai-agent 0.2.0.0] - 2026-08-28++### Added++- `baikai-agent`: three operator-only `policy` keys — `policy.allowed-tools`,+ `policy.max-timeout` (a duration or `"unlimited"`) and+ `policy.max-output-limit` (a byte count or `"unlimited"`) — each defaulting+ from `defaultAgentCeiling`, and all six ceiling fields now printed by+ `agent show` and carried in its `--json` object.++- `baikai-agent`: `Baikai.Agent.Config.repositoryScopeViolations`, which reads+ the resolution report to say which values the untrusted repository file was+ not allowed to supply at all. `Baikai.Agent.Cli` concatenates its answer with+ the pure ceiling's, so an operator sees one refusal naming every problem.++### Changed++- `baikai-agent` (breaking): `AgentConfigScope`'s constructors are+ `AgentUserScope` and `AgentRepositoryScope`. `UserScope` collided with+ `baikai-kit`'s `KitScope` constructor of the same name, the one clash between+ two baikai-family packages. (REV-2 G.5.)++- `baikai-agent` (breaking): a relative `working-dir` resolves against the+ repository root rather than the process's own directory, so `working-dir "."`+ means the checkout whichever file declared it. Resolving against the process+ directory made `"."` mean two places when two documents defined one job, since+ which one it was depended on which layer won. An absolute path is unchanged.+ (REV-2 F.14.)++- `baikai-agent` (breaking): every `--json` output is now built with `aeson`+ rather than a hand-rolled writer, and `agent show --json` always emits one+ object with the same seven keys — `job`, `outcome` (`shown`, `refused` or+ `failed`), `exitCode`, `message`, `configuration`, `ceiling`, `command` —+ with `null` for the parts that do not apply. Previously a refusal emitted a+ different shape from a success and a document that would not parse emitted a+ bare resolution report or nothing at all, so a reader had to know which+ failure mode it was looking at before it could find the exit code. `run --json`+ keeps its `outcome` values and `list --json` is unchanged. (REV-2 F.14.)++- `baikai-agent` (breaking): `--run-id` or `--require-evidence` without either+ `--evidence-file` or `--json` is now a usage error (64) naming both fixes.+ Before, the record was built — a `--version` probe of the tool and two digests+ — and then dropped. Under `--json` the record now travels in the envelope as+ `evidence`, encoded by the same `ToJSON` `--evidence-file` writes.++- `baikai-agent`: `agent show` and `agent run` no longer print another job's+ unknown-key warnings, or the operator file's `policy` keys. The declaration+ describes one job and the ceiling is a separate declaration, so `settei` warns+ about both; neither is a mistake and a document with four jobs printed three+ jobs' worth of noise on every run. A misspelled key inside the selected job+ still warns, and a `policy` node in the *repository* document earns exactly one+ notice saying it has no effect. `Baikai.Agent.Config` exports the two filters,+ `relevantWarnings` and `repositoryPolicyNotice`. (REV-2 F.13.)++- `baikai-agent`: an evidence record's `endpoint` resolves a relative executable+ against the job's working directory before probing it, because that is what+ the child execs. A job whose `executable` is `./bin/agent` previously reported+ a path resolved against the parent's own directory, which does not exist.+ `Baikai.Agent.Run` exports `executableForEvidence`. (REV-2 F.13.)++- `baikai-agent`: a failed run's `error_info.message` keeps the last+ `errorInfoStderrTailBytes` (4096) bytes of standard error, prefixed with how+ many earlier bytes were dropped, instead of the whole captured stream — which+ the output limit allows to reach four mebibytes by default. `Baikai.Agent.Run`+ exports the constant. (REV-2 F.13.)++- `baikai-agent`: `--evidence-file` stages through a uniquely named temporary+ file created with `O_EXCL` beside the destination, instead of the destination+ plus `.partial`. A symbolic link planted at the old, guessable name was+ followed, which let an unattended run overwrite a file of the planter's+ choosing. (REV-2 F.13.)++- `baikai-agent` (breaking): an operator configuration file that lies inside the+ repository root is refused with exit 78, naming the file and the root, and no+ ceiling is established. The source list already refused the repository+ *document*; this closes the shape where the repository supplies the *operator*+ document, which both `--user-config .baikai/policy.kdl` and+ `XDG_CONFIG_HOME=$PWD/.baikai` produce. `--user-config`, `XDG_CONFIG_HOME` and+ `HOME` remain the operator's own inputs: the ceiling is exactly as trustworthy+ as the process environment that selects it, and the guide now says so.+ (REV-2 F.4.)++- `baikai-agent` (breaking): an unrecognised key under the operator file's+ `policy` node is an error rather than a warning, naming the file and every+ such key. Everywhere else a forward-compatible file should not stop an older+ binary; under `policy` a misspelling would silently leave the default ceiling+ in force, which for the one node whose purpose is limiting authority is+ indefensible. Two `AgentConfigError` constructors are added,+ `CeilingFileInsideRepository` and `UnknownPolicySetting`.++- `baikai-agent` (breaking): `AgentConfigPaths` gains `repositoryRoot`, the+ directory the process runs in. `--config PATH` chooses which file supplies+ repository-scope settings and does not move the root, because the root is what+ confines a repository-supplied `working-dir`.++- `baikai-agent` (breaking): a repository configuration file may no longer set+ `executable` or a non-empty `extra-dirs`, and its `working-dir` must resolve —+ after following symbolic links — inside the repository root. Each is refused+ with exit 77 naming the setting, or naming both directories. The operator's+ own file and `--set` may still set all three. `executable` turns configuration+ into code execution with the operator's environment and the prompt on standard+ input; `extra-dirs` inside the root adds nothing the working directory does not+ already give, so the only ones a checkout would ask for are outside it.+ (REV-2 F.3.)++### Removed++- `baikai-agent` (breaking): the `BAIKAI_AGENT_EXECUTABLE` environment binding.+ An environment variable is inherited by every child process and is easy to set+ by accident, and naming the program to run is the widest widening there is.+ An operator whose installation is not on `PATH` writes `executable` in their+ own configuration file or passes `--set`.++### Fixed++- `baikai-agent`: a timed-out run now **escalates to `SIGKILL`**. The runner+ interrupts the child's whole process group, then terminates it, then kills it,+ each of the first two stages bounded by the grace period and ended early once+ the leader has been reaped and no member of the group is left. Previously the+ last resort was `terminateProcess` followed by an *unbounded* wait, so a+ coding agent that ignored `SIGTERM` — or a grandchild holding the output pipe+ — hung the run for as long as it chose to live, with the deadline already+ past. Polling the group rather than waiting on the leader alone is also what+ gives a grandchild the same grace the agent gets.++- `baikai-agent`: a timed-out run **reports the output it drained**. `baikai+ agent run` prints it under the same stream discipline a finished run gets, so+ `response=$(baikai agent run job)` under `capture` receives the partial answer+ with `$?` set to 75, and `--json`'s failure envelope carries the same+ `stdout`, `stdoutTruncated`, `stderr` and `stderrTruncated` fields. A drain+ interrupted because something outside the process group still held the pipe+ open keeps its bytes too, reported as truncated.++- `baikai-agent`: the `baikai` command writes its output as **UTF-8 bytes**+ rather than through the locale encoding. Where an unattended run actually+ happens — cron, a systemd unit, a container — the environment says `LANG=C`,+ and on a platform whose locale encoding follows it a single accented character+ in the agent's answer made the write throw after the run had already finished:+ exit 1, answer lost. This mirrors what the prompt read and the prompt write+ have always done.++- `baikai-agent`: the `baikai` executable now links the **threaded runtime**+ (`ghc-options: -threaded` on the `executable baikai` stanza). Without it a+ blocking operating-system call — the `waitpid` inside+ `System.Process.waitForProcess` — stopped every Haskell thread in the+ installed binary, so a job's configured `timeout` could never fire and a+ coding agent that wrote more than one pipe buffer deadlocked against the+ runner's drain threads. Both defects existed only in the shipped executable:+ the test suite was already compiled `-threaded`, so every runner test passed+ under a runtime the binary did not have.++ The suite now proves the runtime the binary ships with rather than its own.+ `baikai-agent/test/BinaryTests.hs` spawns the built executable — cabal builds+ it first and puts it on the suite's `PATH` through+ `build-tool-depends: baikai-agent:baikai` — asserts that `baikai +RTS --info`+ reports `rts_thr`, and runs `baikai agent run` against a stub agent that+ outlives its deadline, requiring exit 75 within seconds and the whole process+ group gone. See+ [docs/adr/0006](docs/adr/0006-a-process-spawning-executable-ships-on-the-threaded-runtime.md).++## [baikai 0.5.0.0] - 2026-08-05++### Added++- `baikai`: new exposed module `Baikai.Agent`, the provider-neutral vocabulary+ for an **unattended coding-agent run** — a run with no terminal and no human,+ which owns its own tool loop, may change files inside directories the caller+ authorized, and returns a process result rather than a `Response`. It defines+ `AgentRunRequest` (with a required `workingDir`), `AgentRunResult`, the+ `AgentCapability` profile (`read-only`, `edit-workspace`, `full-access`),+ `AgentSafety`, the `AgentOutputMode` and `AgentCapturedOutput` output+ discipline, the `AgentCommand` renderer/runner boundary with an explicit+ prompt transport, and the `AgentRenderError` / `AgentRunFailure` taxonomies.++- `baikai`: the operator policy ceiling — `AgentCeiling`,+ `defaultAgentCeiling`, `CeilingViolation`, and the pure `applyAgentCeiling`.+ It returns a request unchanged when it is within the ceiling and reports+ every violation when it is not; it never clamps an over-broad request to the+ permitted value. The default ceiling permits read-only and edit-workspace+ authority and refuses full access and raw provider arguments.++ `Baikai.Agent` itself is vocabulary and pure policy algebra only: it spawns no+ process and renders no command-line flags. Those live in the vendor packages+ and in `baikai-agent`, below. The module is deliberately not re-exported from+ the umbrella `Baikai` module, because its field accessors share names with+ `Baikai.Interactive`, so `import Baikai` continues to compile unchanged.++- `baikai`: new exposed module `Baikai.Evidence`, the vocabulary for+ **verifiable model-call evidence** — a record of what actually crossed the+ boundary to a provider, as opposed to what the process was configured to ask+ for. It defines `ModelCallEvidence` and the `evidenceSchemaVersion` string+ consumers pin against, `Observed` (a deliberate non-`Maybe` for a value the+ provider either did or did not report, with no function that supplies a+ default), `ThinkingTranslation` with its `ThinkingMode` and+ `ThinkingAdjustment` enumerations describing what a requested+ reasoning-effort level actually became on the wire and every clamp, collapse,+ or drop applied on the way, `EndpointIdentity` and `TransportKind`,+ `CallStatus`, and the ascending `EvidenceStrength` scale.++ It also provides the canonical hashing core: `canonicalEncode` gives a JSON+ value exactly one byte representation (object keys sorted, no insignificant+ whitespace, numbers normalised so `1`, `1.0`, `1.00`, and `1e0` all encode as+ `1`, and a hand-written string escaper so an aeson upgrade cannot silently+ invalidate a recorded digest); `commitmentDigest` hashes a full request+ envelope, and `configurationDigest` hashes an allow-list projection+ (`configurationProjection`) that keeps configuration and replaces content with+ structural summaries, so two calls that ask the same model the same way about+ different subjects agree. The two digests are separate on purpose: the first+ binds a record to a particular request, the second is safe to compare across+ runs that legitimately differ in content.++ Nothing constructs a `ModelCallEvidence` from a real call yet, and no existing+ behaviour changed. New dependencies: `cryptohash-sha256` and+ `base16-bytestring`, both single-purpose packages chosen over a full+ cryptographic framework.++- `baikai`: `Options` gains an `evidence` field carrying an optional+ `EvidenceRequest` — the caller's run identifier, retry provenance, and how+ strictly they need evidence. A call whose `evidence` is `Nothing`, which is+ every call that does not opt in, behaves exactly as it did before: no digest+ is computed and no evidence is emitted.++- (Entry added 2026-08-27; the behaviour shipped in 0.5.0.0.) `baikai`: **strict+ evidence mode**. `EvidenceStrictness` is `EvidenceBestEffort` or+ `EvidenceRequired !EvidenceStrength`, and a caller who asks for the second+ gets a call that **refuses to start** — before any request is built or any+ connection opened — when the configuration cannot reach the strength asked+ for: `Baikai.Evidence.Build.checkEvidenceRequirements` compares the+ requirement against what the provider can deliver and against the thinking+ translation, and `completeRequest` / `streamRequest` return an error-shaped+ response or a terminal `EventError` instead of dispatching. The gate is+ pre-dispatch by design; that is the only point at which refusing is still+ free.++- (Entry added 2026-08-27; the behaviour shipped in 0.5.0.0.) `baikai`:+ **sink-failure semantics under strict mode**. `Baikai.Evidence.Build`+ exports `onSinkFailure`, `sinkFailureIsFatal` and `sinkFailureError`: a trace+ sink that throws fails an `EvidenceRequired` caller's call, because a record+ the sink did not confirm written is not a record, while a best-effort caller's+ call succeeds with the failure reported on stderr.++- (Entry added 2026-08-27; the behaviour shipped in 0.5.0.0.) **Breaking.**+ `baikai`: `Baikai.Provider.Registry.ApiProvider` gained a fourth field,+ `describeThinking :: Model -> Options -> ThinkingTranslation`, which the+ pre-dispatch strictness gate calls to learn what a provider would do with the+ caller's reasoning-effort request without sending anything. Every third-party+ provider constructed with the `ApiProvider` constructor stopped compiling.+ This was not recorded at the time; it is the defect that made 0.6.0.0 hide the+ constructor behind `apiProvider` so that the next field addition is a minor+ release.++- `baikai`: model-call evidence is now **produced and emitted**. A caller who+ sets `Options.evidence` gets exactly one `call_evidence` line per call from+ their trace sink, under every way a call can end: success, provider failure, a+ consumer that abandons the stream (status `aborted`, not `failed` — an abort+ is the consumer's doing and reporting it as a provider failure would+ misattribute it), and dispatch that found no registered handler.++ New exposed module `Baikai.Evidence.Build` bridges the vocabulary to the+ `Model` and `Options` records: `minimalEvidence` and `prepareEvidence` build a+ record, `dispatchEnvelope` supplies the request envelope for the paths where+ no adapter ran, `sanitizeEndpoint` reduces a base URL to scheme/host/port/path+ with the query string and any userinfo dropped wholesale, and `onSinkFailure`+ is the hook a future release replaces to make a strict caller's call fail when+ the trace sink does.++ Every record this release produces has `strength` `requested_only` and every+ provider-observed field set to `"unobserved"`. That is not a placeholder: it+ is a truthful record for a transport that has not yet been taught to observe+ anything. Later releases teach each transport to observe more.++ (Correction added 2026-08-27: the two paragraphs above describe the release+ inaccurately and are kept as shipped rather than rewritten. `onSinkFailure`+ did not await a future release — it shipped in 0.5.0.0 together with+ `sinkFailureIsFatal` and `sinkFailureError`, which already fail a strict+ caller's call when the sink throws. And not every 0.5.0.0 record has `strength`+ `requested_only`: the provider entries below describe what each transport+ reports, and the HTTP adapters reach `correlated` and `model_observed`.)++ **A caller who does not opt in pays nothing.** With `Options.evidence` absent+ no digest is computed, no call identifier is generated, no evidence event is+ emitted, and the request envelope is never even forced — the gate lives inside+ the shared builder rather than at each adapter's call site, and the envelope+ parameter is deliberately lazy. Both facts are guarded by tests.++- `baikai`: `TraceEvent` gains a `CallEvidence` constructor, encoded as+ `{"kind":"call_evidence", …}`. A consumer whose pattern match over `TraceEvent`+ is exhaustive must add a branch; one with a wildcard is unaffected. Filter for+ it with `jq 'select(.kind == "call_evidence") | .evidence'`. Note that a trace+ line carries its fields alongside the `kind` discriminator rather than nested+ under a `data` key, and that the evidence record inside spells its own fields+ in snake_case — the two encodings differ deliberately, because an evidence+ record must render an absent field as explicit `null` while a trace line drops+ it to stay small.++- `baikai`: `Baikai.Provider.Cli.Internal` — the module the two subprocess+ providers share — gains the vocabulary for reading what a coding-agent CLI+ reported about its own run. `CodexRunReport` and the new+ `parseCodexJsonlStream :: Stream IO ByteString -> IO CodexRunReport` fold the+ `codex exec --json` event stream into its assistant text, its thread+ identifier, and its token counts, instead of concatenating agent-message text+ and discarding everything else. `ClaudeCliReport` and+ `decodeClaudeCliResult` do the same for `claude -p --output-format json`.+ Every field but the message text is optional, because both tools' event+ schemas have changed across versions and an absent field is a genuine absence+ rather than a parse failure. **Breaking** for anyone calling+ `parseCodexJsonlStream` directly: its result type is no longer `Text`. This is+ an internal module and is documented as outside the PVP guarantee.++- `baikai`: `Baikai.Provider.Cli.Internal` also gains `ExecutableIdentity` and+ `executableIdentity`, which resolve a configured executable name to an+ absolute path and read the tool's own `--version` line. The probe is cached+ per resolved name for the lifetime of the process, because spawning it per+ model call would roughly double the process cost of the cheapest possible+ call, and it is bounded by a five-second timeout so a tool that hangs on+ `--version` cannot wedge a model call. (Corrected 2026-08-27: the entry said+ two seconds; `versionProbeMicros` has always been five.) A probe that fails records the version+ as absent rather than failing the call. It is only ever called from inside+ the evidence branch: a caller who asked for no evidence must not pay for a+ process whose only purpose is to describe a tool they were about to run+ anyway.++- `baikai`: `subprocessStrength` and `cliResponseEnvelope`, also in+ `Baikai.Provider.Cli.Internal`. The former derives a subprocess call's+ evidence strength from what the tool reported and **nothing else** — the exit+ status is deliberately not one of its arguments. The latter spells the+ response-commitment envelope with the same three keys, in the same shapes, as+ the two API transports build by hand, so a verifier holding a response can+ recompute the digest without first knowing which transport served it.++- `baikai`: `Baikai.Agent` gains `AgentRunOutcome` and `agentRunOutcome`. It+ pairs what an unattended run did — the existing+ `Either AgentRunFailure AgentRunResult` — with the evidence the runner built+ for it. The evidence is a sibling of the outcome rather than a field on+ `AgentRunResult` because the run that most needs a record is one that did not+ produce a result: a run killed by its own timeout reports+ `Left (RunTimedOut …)`, so a record hanging off the `Right` would be+ unreachable exactly there.++### Fixed++- `baikai`: a `call_evidence` event is now emitted **before** its call's+ terminal `call_finished` or `call_failed`, rather than after. The+ OpenTelemetry sink ends and removes a call's span on the terminal, so under+ the old order its evidence-attribute branch was unreachable from any real+ call and every backend saw a span with no evidence on it — nothing failed,+ the attributes were simply never there. No consumer can have depended on the+ old order, because no consumer has ever seen a `call_evidence` line.++- `baikai`: the `ThinkingFormatOpenAI` Haddock in `Baikai.Compat` listed the+ native `reasoning_effort` vocabulary as `minimal | low | medium | high`, which+ predates `xhigh` and `max`. It now lists all six and states that this shape+ alone sends the canonical baikai level verbatim while the other six clamp+ through `compatibleEffort`. No behaviour changed: the native path's exclusion+ from that clamp is deliberate and is guarded by two named tests in+ `baikai-openai/test/ShapeSpec.hs`. A reader who consulted the comment to+ decide whether `xhigh` was safe to use against OpenAI has until now been told+ something untrue.++### Changed++- **Breaking:** `baikai`: `TerminalPayload` gains an `evidence` field and the two+ terminal smart constructors take it as their new first argument:+ `doneTerminal :: Maybe ModelCallEvidence -> Maybe Text -> StopReason -> Message -> TerminalPayload`+ and `errorTerminal` likewise. `Response` gains the same field. A custom+ provider implementation must pass `Nothing` (or a record it builds through+ `Baikai.Evidence.Build`); a custom `Response` built with the record+ constructor must add `evidence = Nothing`. Code that only pattern-matches on+ these types is unaffected.++- **Breaking:** `baikai`: `CallFinished` gains `cachedInputTokens`,+ `cacheWriteTokens`, `reasoningTokens`, and `totalTokens`. The trace path used+ to drop counts that `Baikai.Cost.Log.CallLogEntry` kept from the same `Usage`+ value, which made the cost log strictly more faithful than the trace.++- **Breaking:** `baikai`: a computed cost of **zero is now reported as zero**+ rather than suppressed, in `CallFinished` and at all three `CallLogEntry`+ construction sites. Previously `usd` was omitted whenever the cost came out at+ zero, so "this call was free" and "baikai could not price this call" were+ indistinguishable — and the subscription-based CLI providers always price at+ zero, so that was the common case rather than a corner. **A cost dashboard+ that treated an absent `usd` as "unpriced" will now count those calls as+ costing zero.** That is the correct reading, but it changes what such a+ dashboard shows.++- **Breaking:** `baikai`: `FromJSON TraceEvent` is written out by hand instead of+ derived. The three pre-existing kinds decode exactly as before; a+ `call_evidence` line fails to parse with a message saying to read it as a+ plain `Data.Aeson.Value`. `ModelCallEvidence` has no `FromJSON` on purpose —+ it embeds a `Cost` whose exact `Rational` amounts encode through an+ approximating `Scientific`, so a decoder would return a different value than+ was encoded — and manufacturing that fidelity would be the precise failure+ this vocabulary exists to eliminate.++- `baikai`: `Baikai.Trace.Sink.renderHuman` renders a `CallEvidence` event as a+ single `EVIDENCE run=… call=… strength=…` line rather than the whole record. A+ human-readable sink is for watching calls go by; the full record is meant to+ be read out of `fileSink` output by a machine.++- `baikai`: call identifiers on the trace path are now globally unique.+ `Baikai.Evidence.newCallId` produces 32 lowercase hexadecimal characters+ carrying 128 bits — 48 bits of Unix time in milliseconds, 48 bits of a+ per-process random seed drawn once from `/dev/urandom`, and a 32-bit counter.+ The previous generator combined the process-start *second* with a+ process-local counter into 16 characters, so two processes started within the+ same second emitted identical identifier sequences; its own documentation+ claimed only per-process uniqueness. Identifiers still sort chronologically+ and are still not secrets.++ `Baikai.Trace.newEventId` keeps its name and signature, delegates to+ `newCallId`, and is now deprecated. Anything that pinned the 16-character+ width — a log parser, a fixture, a column type — must widen to 32.++- `baikai`: `renderCeilingViolation` no longer prints the raw provider arguments+ a `ProviderArgsForbidden` violation carries. It reports how many were+ requested and states that their values are not shown. Raw provider arguments+ are the one part of a job description that can hold a credential — the+ configuration layer classifies the setting secret for that reason — and a+ refusal message that quoted them defeated the classification. The constructor+ keeps its `[Text]` payload so a programmatic caller can still inspect it.++## [baikai-claude 0.5.0.0] - 2026-08-05++### Added++- `baikai-claude`: new exposed module `Baikai.Provider.Claude.Agent` with+ `ClaudeAgentConfig`, `defaultClaudeAgentConfig`, and `claudeAgentCommand`, a+ pure renderer from an unattended `AgentRunRequest` to the `claude` argument+ vector. It maps the capability profile onto `--permission-mode`+ (`plan` / `acceptEdits` / `bypassPermissions`), joins a tool allow-list into+ one `--allowedTools` argument, repeats `--add-dir` per extra directory, always+ emits `-p`, and emits `--no-session-persistence` unless `persistSession` is+ set. The prompt travels on standard input and appears nowhere in the argument+ vector. A request naming a different provider is refused with+ `ProviderMismatch`. Nothing is spawned.++- `baikai-claude`: the Anthropic Messages provider now fills in the evidence+ record it previously left blank. It records the model **Anthropic reported+ running** (read from the `message_start` event, which the adapter already+ decoded for the response id and then discarded), Anthropic's `request-id`+ correlation header, the response id, the token counts Anthropic actually+ reported, and a commitment digest over the assembled response. A field the+ provider did not report stays `"unobserved"` and is never backfilled from the+ request — in particular, a stream that fails before `message_start` reports no+ observed model at all. `strength` is `model_observed` when both the model and a+ correlation identifier arrived, `correlated` when only the identifier did, and+ `requested_only` otherwise; a 2xx status never raises it, because a 200 means+ the request was accepted, not that any particular model ran.+ `fully_observed` is unreachable on this transport, since Anthropic does not+ echo the thinking configuration it applied.++- `baikai-claude`: an evidence record's `thinking` field now describes what the+ caller's reasoning-effort preference actually became on the wire, including+ three downgrades that were previously invisible everywhere in baikai's output:+ asking for thinking on a model that does not advertise `reasoning`+ (`thinking_dropped_unsupported_model`); asking for a level whose token budget+ does not fit under the resolved output-token ceiling+ (`thinking_dropped_budget_exceeded`, carrying both colliding numbers), which is+ reachable by lowering `maxTokens` alone; and asking for `high` on an+ adaptive-thinking model, which sends no effort field and so is+ wire-indistinguishable from taking Anthropic's default depth+ (`effort_omitted`). `minimal` on an adaptive model reports `effort_clamped`,+ because Anthropic's adaptive vocabulary has no `minimal`.++- `baikai-claude`: new exports from `Baikai.Provider.Claude.Sse` —+ `ResponseMetadata` and `capturedHeaderNames` — and from+ `Baikai.Provider.Claude.Api` — `claudeMessagesStreamWith`, `SseDriver`, and+ `anthropicStrength`. Response-header capture is an **allow-list**+ (`request-id`, `x-request-id`, `cf-ray`, in that preference order), not a+ denylist, so a header a future gateway adds is not recorded by default.++- `baikai-claude` and `baikai-openai`: both subprocess providers now fill in the+ evidence record they previously left blank, and both export the translation+ function that describes it — `claudeCliThinking` and `codexCliThinking`. They+ record the session or thread identifier the tool reported, the token counts it+ reported, the model it named when it names one, the resolved executable path+ in place of an endpoint URL, the tool's own `--version` string as the+ implementation version (for this transport the tool *is* the implementation),+ a request commitment over the rendered argument vector, and a response+ commitment over the assembled answer.++ **A zero exit status never raises the strength.** A coding-agent CLI that+ exits zero has demonstrated that it ran and did not crash; it has not stated+ which model served the request. Subprocess calls almost always exit zero, so+ encoding that as corroboration would make the weakest evidence in the system+ look like the strongest. `strength` is `model_observed` only when the tool+ named both an identifier and a model, `correlated` when it named only an+ identifier, and `requested_only` otherwise.++ The two transports differ in how far they can get. `claude` names the model+ that consumed tokens in its result event's `modelUsage` map, complete with a+ context-window variant marker such as `[1m]`, so a Claude CLI run can reach+ `model_observed`. `codex-cli 0.146.0` names no model anywhere in its event+ stream, so **no** Codex CLI run can exceed `correlated` — backfilling the+ `--model` flag baikai passed would report the request as an observation.++- `baikai-claude`: an evidence record's `thinking` field now describes what a+ reasoning-effort request became on the `claude` command line: mode `flag`,+ wire field `--effort`, and an `effort_clamped` adjustment recording the+ `minimal` → `low` collapse, because the tool's `--effort` flag has no+ `minimal`. A caller asking for `minimal` and a caller asking for `low` produce+ byte-identical argument vectors — and therefore identical request commitment+ digests — so the translation is the only place that difference survives.++- **Breaking:** `baikai-claude` and `baikai-openai`: `claudeAgentCommand` and+ `codexAgentCommand` return `(AgentCommand, ThinkingTranslation)` rather than+ `AgentCommand`. The runner deliberately imports no vendor renderer, so it+ cannot derive the translation and has to be handed it. A caller that only+ wants the command writes `fmap fst`. Both modules also export the translation+ function alone — `claudeAgentThinking` and `codexAgentThinking` — for asking+ what a level would become without rendering anything.++### Fixed++- **Loud:** `baikai-claude` and `baikai-openai`: both subprocess providers+ hardcoded `usage = zeroUsage` on every call, so a cost dashboard saw every+ `claude -p` and `codex exec` call as consuming no tokens and costing nothing.+ Both tools report their own token counts and baikai now carries them through,+ normalized into the disjoint `Usage` convention: `claude`'s counts are+ Anthropic-shaped and already disjoint, while `codex` reports OpenAI-style+ inclusive prompt counts, so its cached tokens are subtracted out of+ `inputTokens`. `claude` additionally reports a `total_cost_usd`, which now+ populates `Usage.cost` exactly rather than being reported as zero.++ **A dashboard that read these calls as free will now see real tokens and, for+ `claude`, a real cost.** That is the correction, not a regression — but it+ changes what existing reports show, and totals over historical data will not+ match totals over new data.++- `baikai-claude`: `Response.responseId` was always `Nothing` on the `claude -p`+ transport even though `ClaudeCliResult` decoded the tool's `session_id` one+ screen earlier and then dropped it. It now carries that identifier, on both+ the successful and the failed terminal. `baikai-openai`: the same for+ `codex exec`, whose thread identifier was filtered out of the event stream+ along with everything that was not an `agent_message`. These are the handles+ each vendor's support tooling looks a run up by.++### Changed++- **Breaking:** `baikai-claude`: `Baikai.Provider.Claude.Sse`'s four streaming+ entry points — `claudeSseStream`, `claudeSseStreamValue`,+ `claudeSseStreamValueWithHeaders`, and `sseFromResponse` — take a new+ `ResponseMetadata -> IO ()` callback immediately before the existing per-event+ callback. It fires exactly once, before the first event, on both the success+ and the non-2xx path. Pass `(\_ -> pure ())` to keep the previous behaviour.+ The callback is separate rather than a widening of the per-event one because+ the per-event callback runs once per SSE frame and response-level data does not+ belong on that path.++- **Breaking:** `baikai-claude`: `Baikai.Provider.Claude.Internal.Request`'s+ `mapRequest` now returns+ `Either Text (Messages.CreateMessage, ThinkingTranslation)` and+ `computeThinking` returns `(ThinkingPlan, ThinkingTranslation)`. Take `fst` to+ keep the previous value. This module is exposed for provider tests and+ debugging and its header states it is not covered by PVP compatibility+ guarantees, but the change is recorded here because that is not a licence to+ break a consumer silently.++- **Breaking:** `baikai-claude`: `claudeInteractiveCommand` now returns+ `Either AgentRenderError (FilePath, [String])` and `launchClaudeInteractive`+ returns `IO (Either AgentRenderError InteractiveLaunchResult)`. A request+ whose `safety` is a `CodexSandbox` policy — which Claude Code cannot express+ — is refused with `SafetyNotExpressible AgentClaude`, naming the rejected+ sandbox mode and approval policy and suggesting `ClaudeAllowedTools` or+ `DefaultSafety`. Previously the policy was silently discarded and an+ **unrestricted** Claude session was started and reported as a success. A+ `Left` means no process was started; a `Right` with a non-zero exit code+ means the session ran and exited non-zero. `DefaultSafety` and an empty+ `ClaudeAllowedTools` list still render no safety flag and are never refused,+ and no previously rendered argument vector changed. Callers must handle the+ refusal branch.++## [baikai-openai 0.5.0.0] - 2026-08-05++### Added++- `baikai-openai`: new exposed module `Baikai.Provider.OpenAI.Agent` with+ `CodexAgentConfig`, `defaultCodexAgentConfig`, and `codexAgentCommand`, the+ same renderer for `codex exec`. It maps the capability profile onto+ `--sandbox` (`read-only` / `workspace-write` / `danger-full-access`), emits+ `--cd` for the working root, and defaults `--skip-git-repo-check` and+ `--ephemeral` on. A request carrying a tool allow-list is **refused** with+ `UnsupportedToolRestriction`, because `codex exec` has no such flag and running+ it with unrestricted tools would grant more authority than the caller asked+ for. Nothing is spawned.++- `baikai-openai`: an evidence record's `thinking` field now describes what the+ caller's reasoning-effort preference became on the wire for the specific host+ the call went to, across **all seven** OpenAI-compatible wire shapes. The+ OpenAI-native shape sends the canonical level verbatim and records no+ adjustment, because it expresses every level exactly. The four shapes that+ carry an effort word for a non-native host record `effort_clamped` whenever+ the word differs from the canonical name — `minimal` becomes `low`, and both+ `xhigh` and `max` become `high`. Z.ai and Qwen accept a bare+ `enable_thinking: true` with no depth, so **every** level records+ `effort_collapsed_to_toggle`: a caller asking for `max` and a caller asking+ for `low` produce byte-identical requests there, and only the evidence record+ can tell them apart. A host with no reasoning controls records+ `thinking_dropped_unsupported_host` where the option previously vanished with+ no trace. A forty-two-row table test pins the translation and the shaped+ request body for every shape at every level.++- `baikai-openai`: the Chat Completions provider now fills in the evidence record+ it previously left blank. It records the model **the host reported running**+ (read from the first streamed chunk carrying a top-level `model` field and+ never overwritten by a later one), the host's `x-request-id` correlation+ header, the response id, the token counts the host actually reported, and a+ commitment digest over the assembled response. A field the host did not report+ stays `"unobserved"` and is never backfilled from the request — in particular,+ a call that fails before any chunk arrives reports no observed model at all.+ `strength` is `model_observed` when both the model and a correlation+ identifier arrived, `correlated` when only the identifier did, and+ `requested_only` otherwise; a 2xx status never raises it, because a 200 means+ the request was accepted, not that any particular model ran.+ `fully_observed` is unreachable on this transport, since no host in this+ ecosystem echoes the reasoning configuration it applied.++- `baikai-openai`: new exports from `Baikai.Provider.OpenAI.Sse` —+ `ResponseMetadata` and `capturedHeaderNames` — and from+ `Baikai.Provider.OpenAI.Api` — `openaiChatStreamWith` and `SseDriver`.+ Response-header capture is an **allow-list** (`x-request-id`, `request-id`,+ `x-amzn-requestid`, `x-ms-request-id`, `cf-ray`, in that preference order),+ not a denylist, so a header a future gateway adds is not recorded by default.+ The list is longer than the Anthropic one because this transport speaks to an+ open-ended set of hosts and the gateways commonly in front of them.++- `baikai-openai`: the same field for `codex exec`: mode `flag`, wire field+ `model_reasoning_effort`, and **no** adjustments at any level. Codex is the+ only transport in baikai that expresses all six canonical levels exactly, and+ a test asserts each one reaches the command line verbatim.++### Fixed++- `baikai-openai`: `Response.responseId` was always `Nothing` on the Chat+ Completions transport, although every compatible host sends a top-level `id`+ on every streamed chunk. It now carries the identifier the host reported, on+ both the successful and the failed terminal.++### Changed++- **Breaking:** `baikai-openai`: `Baikai.Provider.OpenAI.Sse`'s four streaming+ entry points — `openaiSseStream`, `openaiSseStreamValue`,+ `openaiSseStreamValueWithHeaders`, and `sseFromResponse` — take a new+ `ResponseMetadata -> IO ()` callback immediately before the existing per-chunk+ callback. It fires exactly once, before the first chunk, on both the success+ and the non-2xx path — a failed call's correlation identifier is if anything+ more valuable than a successful one's. Pass `(\_ -> pure ())` to keep the+ previous behaviour. The callback is separate rather than a widening of the+ per-chunk one because that one runs once per SSE frame and response-level data+ does not belong on that path.++- **Breaking:** `baikai-openai`: `Baikai.Provider.OpenAI.Api`'s `RawChunk` gains+ `model` and `responseId` fields, both `Maybe Text`. Code that pattern-matches+ on `RawChunk` is unaffected; code that constructs one with record syntax must+ add them.++- **Breaking:** `baikai-openai`: `Baikai.Provider.OpenAI.Shape`'s+ `shapeRequestBody`, `streamRequestBody`, and `injectThinkingShape` now return+ `(Aeson.Value, ThinkingTranslation)` instead of a bare body. Take `fst` to+ keep the previous value. The description has to travel out of the shaping step+ because nothing downstream can recompute it: it depends on the host's+ `ThinkingFormat`, which only the compat lookup knows. **No request body+ changed** — every one of the seven shapes puts exactly the same bytes on the+ wire as before.++- **Breaking:** `baikai-openai`: `codexInteractiveCommand` now returns+ `Either AgentRenderError (FilePath, [String])` and `launchCodexInteractive`+ returns `IO (Either AgentRenderError InteractiveLaunchResult)`. A request+ whose `safety` is a non-empty `ClaudeAllowedTools` list — which `codex` has+ no flag for — is refused with `SafetyNotExpressible AgentCodex`, quoting the+ rejected tools and suggesting `CodexSandbox` or `DefaultSafety`. Previously+ the allow-list was silently discarded and Codex was started with its default+ sandbox. The same `Left`/`Right` reading applies, `DefaultSafety` and an+ empty allow-list are never refused, and no previously rendered argument+ vector changed. Callers must handle the refusal branch.++ Both changes make the interactive surface honor the same contract as the new+ unattended surface: a safety policy the chosen provider cannot express fails+ visibly instead of silently becoming a weaker policy. Downstream consumers+ must adapt before upgrading; the known one is `shinzui/seihou`, whose+ `Seihou.CLI.AgentLaunchExec` module builds interactive launch requests.++## [baikai-trace-otel 0.3.0.3] - 2026-08-05++### Added++- `baikai-trace-otel`: the sink attaches an evidence record's salient fields to+ the open span as flat attributes (`baikai.evidence.run_id`,+ `baikai.evidence.call_id`, `baikai.evidence.strength`, the two digests, and+ `gen_ai.response.model` only when the provider actually reported one) rather+ than serialising the record into one blob. A `CallEvidence` event neither+ opens nor closes a span.++### Changed++- `baikai-trace-otel`: widened its `baikai` bound to admit `0.5`. No API change.++## [baikai-effectful 0.3.0.3] - 2026-08-05++### Changed++- Widened its `baikai` bound to admit `0.5`. No API change; the package's+ own surface is untouched.++## [baikai-kit 0.1.0.4] - 2026-08-05++### Changed++- Widened its `baikai` bound to admit `0.5`. No API change; the package's+ own surface is untouched.++## [baikai-agent 0.1.0.0] - 2026-08-05++### Added++- `baikai-agent`: **new package** (`0.1.0.0`) holding the unattended+ coding-agent runner. `Baikai.Agent.Run.runAgentCommand` takes an+ `AgentRunRequest` and an already-rendered `AgentCommand` and spawns the tool+ with no terminal and no human present. It delivers the prompt on standard+ input and closes the handle, drains standard output and standard error+ concurrently so a chatty agent cannot deadlock on a full pipe, retains at most+ `outputLimit` bytes per stream while reading and discarding the excess, and+ honors the three output disciplines. Preconditions run before any spawn: a+ missing working directory is `WorkingDirMissing` and unset or empty declared+ variables are `MissingEnvironment`, listing all of them at once. On timeout+ the child's whole process group is interrupted, given a grace period, and then+ terminated, so the agent's own child processes go with it; the failure reports+ the configured limit. A non-zero exit code is a successful run carrying that+ code, not a failure. The runner consumes an already-rendered `AgentCommand`+ and never imports a vendor renderer, so it is exercised entirely with+ hand-written argument vectors. Its POSIX-signal escalation is conditional on a+ non-Windows build.++- `baikai-agent`: new exposed module `Baikai.Agent.Config`, the layered+ configuration layer. `resolveAgentJob` resolves one named job across five+ layers — built-in defaults, the operator file, the repository file, the+ environment, then command-line overrides, later layers winning — and returns+ the resolved `AgentJob` together with a report attributing every value to the+ file, line, and column it came from. `agentJobRequest` converts a job into an+ `AgentRunRequest`, taking the prompt at call time. `listAgentJobs` enumerates+ configured job names, sorted, each attributed to the highest-precedence scope+ defining it. `defaultAgentConfigPaths` locates+ `$XDG_CONFIG_HOME/baikai/agents.kdl` (or `$HOME/.config/baikai/agents.kdl`)+ and `./.baikai/agents.kdl`, with no upward search through parent directories.++ The **policy ceiling** is loaded by a separate function, `loadAgentCeiling`,+ against a separate source list containing the operator file and nothing else:+ no repository file, environment variable, or command-line override can raise+ it. `applyCeilingToJob` refuses an over-broad request with `CeilingRejected`+ rather than clamping it. With no operator file the ceiling is+ `defaultAgentCeiling`. `safety.provider-args` is classified secret and renders+ as `<redacted>` in any report or structured error.++ New dependencies: `settei`, `settei-env`, `settei-kdl`, and+ `settei-optparse-applicative` (all `^>=0.2`, published on Hackage at+ `0.2.0.0`), plus `containers` and `filepath`. `settei-formats` is deliberately+ excluded, because it bundles Dhall loading and repository configuration is+ untrusted input here.++- `baikai-agent`: the **`baikai` executable**, with the `agent run`,+ `agent show`, and `agent list` commands, and the `Baikai.Agent.Cli` module+ that implements them. A shell script now invokes one stable command, supplies+ a prompt on standard input, and selects Claude Code or Codex entirely through+ configuration.++ `agent run` resolves the named job, caps it against the operator ceiling,+ renders it through the vendor renderer for its provider, and spawns it. The+ agent's own exit code passes through unchanged; Baikai's own failures use 64+ and above following the `sysexits` convention — 64 for a usage error or an+ empty prompt, 69 when the executable could not be started, 70 for malformed+ output, 75 for a timeout, 77 for a policy refusal, and 78 for a configuration+ problem. The prompt comes from `--prompt-stdin`, `--prompt-file`, or+ `--prompt`, which are mutually exclusive, and is decoded as UTF-8 explicitly+ rather than through the handle's locale encoding.++ `agent show` performs the whole pipeline except spawning and prints each+ resolved value with the file, line, and column it came from, the policy+ ceiling in force and where it was read, and the exact argument vector that+ would be spawned — with `<redacted>` in place of any raw provider argument. A+ job whose policy is refused prints its configuration first and then the+ refusal. `agent list` enumerates configured jobs and the scope each came from.++ Every Baikai diagnostic goes to standard error. The agent's own output follows+ the job's output mode, so `response=$(baikai agent run job)` yields the+ agent's answer alone for a capturing job. `--set KEY=VALUE` overrides one+ setting of the selected job through `settei`'s own command-line source, so an+ override is attributed with the same fidelity as a file. `--json` emits+ exactly one JSON object per command.++ New dependencies for `baikai-agent`: `baikai-claude`, `baikai-openai`, and+ `optparse-applicative`. The provider packages are needed only so that+ `renderJobCommand`, the single provider dispatch point in the codebase, can+ reach both renderers. This is the first dependency in the workspace from+ `baikai-agent` onto the provider packages, so `baikai-agent` now publishes+ after all three of `baikai`, `baikai-claude`, and `baikai-openai`.++ The user guide `docs/user/unattended-agent-runs.md` documents the whole+ surface: the three commands with their flags, exit codes, and stream+ discipline; the KDL job format and layer precedence; the operator ceiling and+ redaction; the capability mapping tables for both tools; and a before-and-after+ migration of a script that embeds provider flags today.+ `docs/user/cli-providers.md` and `docs/user/interactive-launches.md` link to+ it, and the capability mapping tables moved there from the latter.++- `baikai-agent`: **an unattended coding-agent run now produces model-call+ evidence.** This surface previously had no observability of any kind: no trace+ sink, no `Response`, no usage, no identifiers. An operator could show that a+ process started, exited, and took some time; they could not show which model+ ran, which reasoning effort was applied, or which agent session the run+ corresponds to in the vendor's records.++ A record carries the run and call identifiers, the resolved executable and its+ own reported version, digests over the request, the requested model and what+ the reasoning-effort request became on the command line, whatever the tool+ reported about itself, the outcome, and an honest strength.++ **A zero exit status never raises the strength.** On this surface that rule+ matters more than anywhere else, because almost every unattended run exits+ zero. A coding agent that exits zero has demonstrated that it ran, not which+ model served it.++ Two things gate what a record can prove, and neither is the default. The job+ must **capture** output — under `inherit` the agent's bytes went to the+ operator's terminal and baikai never held them — and the tool must be+ configured to print a structured format, which means `--output-format json`+ for `claude` or `--json` for `codex exec` through the job's `provider-args`.+ Without both, the tool's session identifier, model, and token counts are+ genuinely unavailable and the record says `"unobserved"` rather than inferring+ anything. A timed-out run records `aborted`; a run that never started records+ nothing at all.++- **Breaking:** `baikai-agent`: `Baikai.Agent.Run.runAgentCommand` takes two new+ leading arguments and returns the new outcome type:+ `Maybe EvidenceRequest -> ThinkingTranslation -> AgentRunRequest -> AgentCommand -> IO AgentRunOutcome`.+ A caller who wants the previous behaviour passes `Nothing` and+ `Baikai.Evidence.noThinkingRequested` and reads the `outcome` field; that path+ is byte-for-byte what it was, and costs what it cost — no digest is computed,+ no call identifier is generated, and the tool is not invoked a second time to+ read its version.++- `baikai-agent`: `baikai agent run` gains `--evidence-file PATH` and+ `--run-id TEXT`. Supplying neither leaves the run on the pre-existing path at+ the pre-existing cost; supplying either turns recording on, with the job's own+ name standing in as the run identifier when only a destination is given. The+ file is written atomically — a staging file beside the destination, then a+ rename — so a reader polling the path never sees a half-written object, and it+ is never appended to. A failed write is reported on standard error and never+ changes the exit code, because the agent's own status is what a calling script+ branches on. `docs/user/unattended-agent-runs.md` documents both options and,+ more importantly, what the record does and does not prove.++- `baikai-agent`: `baikai agent run` gains `--require-evidence STRENGTH`, taking+ `requested_only`, `correlated`, `model_observed`, or `fully_observed` — the+ same words a record's `strength` field spells, so what one record showed can+ be passed back as the next run's requirement. A job whose configuration cannot+ produce evidence of at least that strength is refused before anything is+ spawned, exiting 77 — the code a ceiling violation and an inexpressible safety+ policy already use, so a script branching on 77 needs no new case.++## [baikai-claude 0.4.0.1] - 2026-07-30++### Fixed++- Widened the `crypton` bound from `^>=1.0` to `>=1.0 && <1.2` so consumers can+ build `baikai-claude` alongside packages that require `crypton` 1.1.x (for+ example `pg-migrate-1.1.0.0`), which previously had no solvable build plan.+ The only `crypton` use is `Crypto.Hash` (`Digest`, `SHA256`) in+ `Baikai.Provider.Claude.Transport`, whose API is identical across the 1.0/1.1+ boundary. No API change.++## [baikai 0.4.1.0] - 2026-07-20++### Changed++- Version bump only; no library API or code changes. Released so the umbrella+ release tag `baikai-0.4.1.0` names a fresh core version alongside the breaking+ `baikai-claude` / `baikai-openai` 0.4.0.0 releases, matching the tag+ convention downstream consumers pin against.++## [baikai-claude 0.4.0.0] - 2026-07-20++### Changed++- **Breaking:** `claudeCliCommand` now takes the `Options` record and forwards+ `Options.thinking` to batch `claude -p` as `--effort <level>` (`minimal`+ collapses to `low`, matching the interactive launcher and the claude CLI's+ lack of a `minimal` value). `thinking = Nothing` emits no effort flag, keeping+ existing argv byte-for-byte. The added parameter is a PVP-major signature+ change.++## [baikai-openai 0.4.0.0] - 2026-07-20++### Changed++- **Breaking:** `codexCliCommand` now takes the `Options` record and forwards+ `Options.thinking` to `codex exec` as `-c model_reasoning_effort=<level>` for+ all six effort levels. `thinking = Nothing` emits no override, keeping+ existing argv byte-for-byte. The added parameter is a PVP-major signature+ change.++## [baikai 0.4.0.0] - 2026-07-20++### Added++- Added `ThinkingXHigh` and `ThinkingMax` to the exported `ThinkingLevel`+ vocabulary and added a defaulted `InteractiveLaunchRequest.effort` field.+ Extending the closed sum type is a PVP-major API change for downstream+ exhaustive matches.++## [baikai-claude 0.3.0.2] - 2026-07-20++### Added++- Added `--effort` rendering to interactive Claude Code launches and preserved+ `xhigh` / `max` on native adaptive Anthropic API requests, with larger fixed+ budgets for manual-thinking models.++### Changed++- Bumped the internal `baikai` dependency bound to `^>=0.4.0` for the+ baikai 0.4.0.0 release.++## [baikai-openai 0.3.0.2] - 2026-07-20++### Added++- Added `model_reasoning_effort` overrides to interactive Codex launches and+ preserved `xhigh` / `max` in native OpenAI request JSON; non-native+ OpenAI-compatible request shapes continue to clamp them to `high`.++### Changed++- Bumped the internal `baikai` dependency bound to `^>=0.4.0` for the+ baikai 0.4.0.0 release.++## [baikai-trace-otel 0.3.0.2] - 2026-07-20++### Changed++- Bumped the internal `baikai` dependency bound to `^>=0.4.0` for the+ baikai 0.4.0.0 release. No API changes.++## [baikai-effectful 0.3.0.2] - 2026-07-20++### Changed++- Bumped the internal `baikai` dependency bound to `^>=0.4.0` for the+ baikai 0.4.0.0 release. No API changes.++## [baikai-kit 0.1.0.3] - 2026-07-20++### Changed++- Bumped the internal `baikai` dependency bound to `^>=0.4.0` for the+ baikai 0.4.0.0 release. No API changes.++## [baikai 0.3.1.0] - 2026-07-15++### Added++- Added `claude-sonnet-5` to the Anthropic model catalog (1M context window,+ 128k max output, `tool_call` + reasoning).+- Added the `gpt-5.6` family — `gpt-5.6`, `gpt-5.6-luna`, `gpt-5.6-sol`, and+ `gpt-5.6-terra` — to the OpenAI model catalog (chat-completions with+ `tool_call` support).++### Changed++- Corrected `claude-sonnet-4-5` context window to 1M tokens and+ `claude-sonnet-4-6` max output to 128k tokens in the catalog.+- Added PVP-compliant upper bounds to all previously-unbounded library and+ executable dependencies.++## [baikai-claude 0.3.0.1] - 2026-07-15++### Changed++- Added PVP-compliant upper bounds to all previously-unbounded library and+ executable dependencies.++## [baikai-openai 0.3.0.1] - 2026-07-15++### Changed++- Added PVP-compliant upper bounds to all previously-unbounded library and+ executable dependencies.++## [baikai-trace-otel 0.3.0.1] - 2026-07-15++### Changed++- Added PVP-compliant upper bounds to all previously-unbounded library and+ executable dependencies.++## [baikai-effectful 0.3.0.1] - 2026-07-15++### Changed++- Added PVP-compliant upper bounds to all previously-unbounded library and+ executable dependencies.++## [baikai-kit 0.1.0.2] - 2026-07-15++### Changed++- Added PVP-compliant upper bounds to all previously-unbounded library and+ executable dependencies.++## [baikai 0.3.0.0] - 2026-07-03++### Added++- Added the documented record-update bases `emptyOptions`, `emptyContext`,+ `emptyModel`, `emptyResponse`, `emptyTool`, `emptyTextContent`,+ `emptyThinkingContent`, `emptyToolCall`, `emptyImageContent`,+ `emptyEmbeddingModel`, plus zero-valued bases `zeroUsage`, `zeroCost`,+ `zeroCostBreakdown`, and `zeroModelCost`.+- Added `firstEmbedding`, a total accessor for OpenAI-compatible embedding+ responses.+- Added `responseError`, `errorResponse`, `httpError`, and+ `parseRetryAfterSeconds` for the in-band error contract.++### Changed++- **Breaking:** Constructors for evolvable records are no longer exported:+ `Options`, `Context`, `Model`, `OpenAICompletionsCompat`,+ `AnthropicMessagesCompat`, and `InteractiveLaunchRequest` are built from+ exported base values plus record updates.+- **Breaking:** The `_X` base values are deprecated in favor of the new+ `empty*` and `zero*` names; the aliases remain for this release.+- **Breaking:** Removed `unModel`; use `mkModel` or `emptyModel` record+ updates.+- **Breaking:** Renamed `InteractiveLaunchRequest.model` to `modelId`.+- **Breaking:** `Response.latencyMs` and trace event `latencyMs` fields are+ now `Int`.+- **Breaking:** `completeRequest` / `completeRequestWith` no longer throw+ `BaikaiError` for unregistered API tags; they return an error-shaped+ `Response`.+- **Breaking:** CLI providers now report subprocess/decode/provider failures+ in-band as error-shaped `Response`s.+- **Breaking:** `errorTerminal` now requires a `BaikaiError`, enforcing+ structured error details for `EventError` construction sites.+- Documented that `Baikai.Prelude` is a convenience module outside the PVP+ stability contract and that `.Internal` modules have no compatibility+ guarantees.++### Fixed++- Empty embedding `data` arrays now produce a typed `decodeError` instead of+ crashing on an empty vector.+- The model-fetch JSON renderer now delegates string escaping to aeson.+- The model generator now fails on sanitized Haskell identifier collisions+ instead of rendering duplicate bindings.+- Live HTTP status, `Retry-After`, and network-failure classification now+ works on both API providers.+- `content_filter` / Anthropic refusals terminate as classified `EventError`+ terminals, and `liftCompleteToStream` preserves error-shaped responses.++## [baikai-claude 0.3.0.0] - 2026-07-03++### Changed++- **Breaking:** `Baikai.Provider.Claude.ErrorClass` moved to+ `Baikai.Provider.Claude.Internal.ErrorClass`.+- **Breaking:** `mapRequest` and pure request-shaping helpers moved from+ `Baikai.Provider.Claude.Api` to+ `Baikai.Provider.Claude.Internal.Request`.+- **Breaking:** `ClaudeCliConfig` and `ClaudeInteractiveConfig` constructors+ are no longer exported; start from their default config values and update+ fields.+- **Breaking:** CLI and interactive `extraArgs` fields are now `[Text]`.++## [baikai-openai 0.3.0.0] - 2026-07-03++### Changed++- **Breaking:** `Baikai.Provider.OpenAI.ErrorClass` moved to+ `Baikai.Provider.OpenAI.Internal.ErrorClass`.+- **Breaking:** `mapRequest` and pure request-shaping helpers moved from+ `Baikai.Provider.OpenAI.Api` to+ `Baikai.Provider.OpenAI.Internal.Request`.+- **Breaking:** `CodexCliConfig` and `CodexInteractiveConfig` constructors are+ no longer exported; start from their default config values and update fields.+- **Breaking:** CLI and interactive `extraArgs` fields are now `[Text]`.++## [baikai-trace-otel 0.3.0.0] - 2026-07-03++### Changed++- Updated the `baikai` dependency bound to `^>=0.3.0`.+- Adjusted to the core trace event `latencyMs :: Int` type.++## [baikai-effectful 0.3.0.0] - 2026-07-03++### Changed++- Updated the `baikai` dependency bound to `^>=0.3.0`.++## [baikai-kit 0.1.0.1] - 2026-07-03++### Changed++- Updated the `baikai` dependency bound to `^>=0.3.0`.++## [baikai 0.2.0.0] - 2026-06-21++### Added++- `Usage`, `Cost`, and `CostBreakdown` now have `Semigroup`/`Monoid`+ instances that add field-by-field, plus `sumUsage :: Foldable f => f+ Usage -> Usage`, so callers can total per-call usage and cost.+ `reasoningTokens` combines as presence-wins (`Nothing` only when both+ operands are `Nothing`).+- A categorised error model: `BaikaiError` is now a record carrying an+ `ErrorCategory` (`AuthError`, `RateLimited`, `ContextOverflow`,+ `InvalidRequest`, `TransientError`, `DecodeFailure`, `ProcessFailure`,+ `ProviderUnavailable`, `OtherError`), an optional HTTP `httpStatus`, a+ `retryAfterSeconds` hint, and a subprocess `exitCode`. New smart+ constructors (`providerError`, `invalidRequest`, `decodeError`,+ `processError`, `rateLimited`, `authError`, `providerUnavailable`),+ the `isRetryable` predicate, and the pure `classifyHttpStatus` /+ `classifyHttpStatusWithBody` helpers let callers implement retry+ policy without parsing error text. `ErrorCategory` and `BaikaiError`+ serialize to JSON.+- `Response` and the streaming `EventError`'s `TerminalPayload` now+ carry `errorInfo :: Maybe BaikaiError`, so a failed `completeRequest`+ (or a drained stream) exposes the structured category/retry hint+ in-band. `Baikai.Stream.Event` gains `doneTerminal` / `errorTerminal`+ constructors.++### Changed++- **Breaking:** `BaikaiError`'s four flat constructors+ (`ProviderError`, `RequestInvalid`, `DecodeError`, `ProcessError`)+ were replaced by the record above. Migrate by lowercasing to the+ smart constructors — `ProviderError "x"` becomes `providerError "x"`,+ `ProcessError n "x"` becomes `processError n "x"`, etc.+- **Breaking:** `Baikai.Stream.Event.TerminalPayload` and+ `Baikai.Response.Response` gained an `errorInfo` field; build+ `TerminalPayload` via `doneTerminal` / `errorTerminal`.++### Fixed++- Restored JSON decoding for `BaikaiError` values with omitted optional+ metadata fields.++## [baikai-claude 0.2.0.0] - 2026-06-21++### Added++- The Anthropic API and `claude -p` CLI providers now classify failures+ into the typed `BaikaiError` categories: HTTP errors (via the caught+ `servant-client` `ClientError`) map status/`Retry-After`/body onto+ `AuthError` / `RateLimited` / `ContextOverflow` / `InvalidRequest` /+ `TransientError`, and mid-stream Anthropic `error` events are+ classified by their error type. The result is surfaced on+ `Response.errorInfo`.++## [baikai-openai 0.2.0.0] - 2026-06-21++### Added++- The OpenAI/OpenAI-compatible API and `codex exec` CLI providers now+ classify failures into the typed `BaikaiError` categories the same way+ as `baikai-claude` (HTTP `ClientError` for status-based errors,+ streamed error text for mid-stream errors), surfaced on+ `Response.errorInfo`.++## [baikai-trace-otel 0.2.0.0] - 2026-06-21++### Changed++- Updated the `baikai` dependency bound to `^>=0.2.0` for compatibility with+ the `baikai 0.2.0.0` breaking API release.++## [baikai-effectful 0.2.0.0] - 2026-06-21++### Changed++- Updated the `baikai` dependency bound to `^>=0.2.0` for compatibility with+ the `baikai 0.2.0.0` breaking API release.++## [baikai 0.1.1.0] - 2026-06-12++### Added++- Added provider-agnostic `ResponseFormat` support on `Options`, including+ plain JSON-object mode and named JSON-schema mode.+- Added `Baikai.Embedding`, an OpenAI `/v1/embeddings` client for text+ embeddings.++## [baikai-claude 0.1.1.0] - 2026-06-12++### Added++- Mapped baikai `ResponseFormat` options onto Anthropic `output_config` for+ Claude API requests.+- Exported `mapRequest` for request-mapping tests and downstream inspection.++## [baikai-openai 0.1.1.0] - 2026-06-12++### Added++- Mapped baikai `ResponseFormat` options onto OpenAI Chat Completions+ `response_format`.+- Exported `mapRequest` for request-mapping tests and downstream inspection.++## [baikai-effectful 0.1.0.0] - 2026-06-12++### Added++- Initial release: effectful binding for baikai with the `Baikai` dynamic+ effect, `complete`, `streamCollect`, `streamEach`, and registry-backed+ interpreters.++## [baikai 0.1.0.0] - 2026-06-04++### Added++- Initial release: unified Haskell interface for working with multiple AI+ providers. Core modules including `Baikai`, `Baikai.Prelude`, `Baikai.Api`,+ `Baikai.Provider`, `Baikai.Provider.Registry`, `Baikai.Response`,+ `Baikai.Stream`, `Baikai.Tool`, `Baikai.Trace`, and the cost/usage modules.+- Depends on released `streamly` (`>=0.11 && <0.13`) and `streamly-core`+ (`>=0.3 && <0.5`) from Hackage, so all dependencies resolve from Hackage.++## [baikai-claude 0.1.0.0] - 2026-06-04++### Added++- Initial release: Anthropic Claude providers for the baikai abstraction,+ wrapping the `claude` package for both the Anthropic API and the `claude -p`+ CLI (`Baikai.Provider.Claude.Api`, `.Cli`, `.Interactive`).++## [baikai-openai 0.1.0.0] - 2026-06-04++### Added++- Initial release: OpenAI providers for the baikai abstraction, wrapping the+ `openai` package for OpenAI's Chat Completions API+ (`Baikai.Provider.OpenAI.Api`, `.Cli`, `.Interactive`).++## [baikai-trace-otel 0.1.0.0] - 2026-06-04++### Added++- Initial release: OpenTelemetry `TraceSink` adapter for baikai+ (`Baikai.Trace.Sink.OpenTelemetry`), emitting one OTel span per provider call+ with GenAI semantic-convention attributes plus baikai cost and latency.
+ LICENSE view
@@ -0,0 +1,30 @@+Copyright (c) 2026 Nadeem Bitar++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above+ copyright notice, this list of conditions and the following+ disclaimer in the documentation and/or other materials provided+ with the distribution.++ * Neither the name of Nadeem Bitar nor the names of other+ contributors may be used to endorse or promote products derived+ from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,3 @@+# baikai-mcp++Model Context Protocol client for Baikai. See the module documentation of `Baikai.Mcp.Client`.
+ baikai-mcp.cabal view
@@ -0,0 +1,136 @@+cabal-version: 3.4+name: baikai-mcp+version: 0.1.0.0+synopsis: Model Context Protocol client for Baikai+description:+ A bounded Model Context Protocol (MCP) client. Targets MCP 2026-07-28 over+ stateless Streamable HTTP, detects handshake-era servers, and supports the+ deprecated HTTP+SSE transport when configured explicitly. A host-supplied+ hook approves every transmission and can add credentials; interim results+ that carry only opaque state are continued under a round limit.++homepage: https://github.com/shinzui/baikai+bug-reports: https://github.com/shinzui/baikai/issues+license: BSD-3-Clause+license-file: LICENSE+author: Nadeem Bitar+maintainer: nadeem@gmail.com+category: AI, Network+build-type: Simple+tested-with: ghc ==9.12.4+extra-doc-files:+ CHANGELOG.md+ README.md++common common-options+ ghc-options:+ -Wall+ -Wcompat+ -Widentities+ -Wincomplete-uni-patterns+ -Wincomplete-record-updates+ -Wredundant-constraints+ -fhide-source-paths+ -Wmissing-export-lists+ -Wpartial-fields+ -Wmissing-deriving-strategies++ -- Exhaustiveness is an error, not a warning; see baikai.cabal.+ ghc-options:+ -Werror=incomplete-patterns+ -Werror=incomplete-uni-patterns+ -Werror=incomplete-record-updates++ default-language: GHC2024+ default-extensions:+ DuplicateRecordFields+ MultiWayIf+ OverloadedRecordDot+ OverloadedStrings++library+ import: common-options+ hs-source-dirs: src+ exposed-modules:+ Baikai.Mcp.Auth+ Baikai.Mcp.Client+ Baikai.Mcp.Content+ Baikai.Mcp.Error+ Baikai.Mcp.Internal.Binding+ Baikai.Mcp.Internal.Http+ Baikai.Mcp.Internal.Mux+ Baikai.Mcp.Internal.Sse+ Baikai.Mcp.JsonSchema+ Baikai.Mcp.Prompt+ Baikai.Mcp.Protocol+ Baikai.Mcp.Resource+ Baikai.Mcp.Tool+ Baikai.Mcp.Transport+ Baikai.Mcp.Transport.HttpSse+ Baikai.Mcp.Transport.Stream++ other-modules: Paths_baikai_mcp+ autogen-modules: Paths_baikai_mcp+ build-depends:+ aeson ^>=2.2,+ async ^>=2.2,+ baikai ^>=0.11.0.0,+ base >=4.20 && <5,+ base64-bytestring ^>=1.2,+ bytestring ^>=0.12,+ case-insensitive ^>=1.2,+ containers ^>=0.7,+ crypton >=1.0 && <1.1,+ http-client ^>=0.7,+ http-client-tls >=0.3 && <0.5,+ http-types ^>=0.12,+ memory ^>=0.18,+ network ^>=3.2,+ network-uri ^>=2.6,+ regex-tdfa ^>=1.3.2,+ scientific ^>=0.3,+ stm ^>=2.5,+ text ^>=2.1,+ time ^>=1.14,+ vector ^>=0.13,++test-suite baikai-mcp-test+ import: common-options+ ghc-options: -threaded+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Main.hs+ other-modules:+ AuthSpec+ ClientSpec+ JsonSchemaSpec+ LegacySpec+ McpStub+ ModernHttpSpec+ ProtocolSpec+ ResourcePromptSpec+ StreamSpec+ ToolSpec++ build-depends:+ aeson,+ async,+ baikai,+ baikai-mcp,+ base,+ bytestring,+ case-insensitive,+ containers,+ http-client,+ http-client-tls,+ http-types,+ network,+ process,+ stm,+ tasty,+ tasty-hunit,+ text,+ time,+ vector,+ wai ^>=3.2,+ warp ^>=3.4,
+ src/Baikai/Mcp/Auth.hs view
@@ -0,0 +1,937 @@+-- | Credentials for protected MCP endpoints: static header references and+-- delegated OAuth 2.1 (MCP authorization, revision @2026-07-28@).+--+-- Credentials reach the wire only through the client's per-send+-- 'McpRequestHook', and only for the origin they were configured for.+-- Configuration holds /references/; values are resolved at send time, so+-- a secret rotated behind the same reference takes effect on the next+-- request. Every secret is a 'Secret', whose 'Show' never reveals it.+--+-- A server accepting a credential and the host authorizing an agent's+-- action are separate decisions: this module supplies the first, and a+-- host composes its own policy hook in front of it with '<>'.+--+-- The OAuth flow follows the specification: protected resource metadata+-- (RFC 9728) names the authorization server; its metadata (RFC 8414 or+-- OpenID Connect discovery) must carry the exact issuer it was fetched for+-- and advertise PKCE @S256@; the client registers by pre-registration,+-- then a Client ID Metadata Document, then (deprecated) dynamic+-- registration; authorization uses PKCE, @state@, the @resource@+-- indicator and RFC 9207 issuer validation before any code is redeemed.+-- Tokens are stored per principal and resource and bound to the issuer and+-- client that issued them; refresh is serialized so concurrent requests+-- cause one rotation.+module Baikai.Mcp.Auth+ ( -- * Secrets and references+ Secret,+ secret,+ revealSecret,+ CredentialRef (..),+ CredentialResolver (..),++ -- * Static credentials+ StaticCredentials (..),+ noStaticCredentials,+ staticCredentialHook,++ -- * Challenges+ AuthChallenge (..),+ parseChallenge,++ -- * OAuth configuration+ OAuthConfig (..),+ oauthConfig,+ ClientRegistration (..),+ ApplicationType (..),+ InteractiveAuthorizer (..),+ AuthorizationRequest (..),+ AuthorizationCallback (..),++ -- * Token storage+ TokenSet (..),+ StoredGrant (..),+ TokenStore (..),+ newInMemoryTokenStore,++ -- * The provider+ OAuthProvider,+ newOAuthProvider,+ oauthRequestHook,+ AuthError (..),+ AuthOutcome (..),+ authorizeFromChallenge,+ recoverFromChallenge,++ -- * Loopback authorizer+ LoopbackConfig (..),+ loopbackAuthorizer,++ -- * Helpers+ canonicalResource,+ pkceChallenge,+ )+where++import Baikai.Mcp.Client (McpError (..), McpRequestHook (..), SendAttempt (..), SendDecision (..), sendHeader)+import Baikai.Mcp.Internal.Http (HttpEndpoint (..), parseEndpoint, readBounded, rethrowAsync, statusOf)+import Baikai.Mcp.Transport (isProtocolControlledHeader)+import Control.Concurrent.MVar+import Control.Exception (SomeException, bracket, try)+import Control.Monad (forM_, unless, when)+import Crypto.Hash (SHA256 (..), hashWith)+import Crypto.Random (getRandomBytes)+import Data.Aeson (Value (..), object, (.=))+import Data.Aeson qualified as Aeson+import Data.Aeson.KeyMap qualified as KeyMap+import Data.ByteArray qualified as BA+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Base64 qualified as B64+import Data.ByteString.Base64.URL qualified as B64URL+import Data.ByteString.Builder qualified as Builder+import Data.ByteString.Char8 qualified as BS8+import Data.ByteString.Lazy qualified as LBS+import Data.CaseInsensitive qualified as CI+import Data.Char (isAlphaNum, isAscii, isSpace)+import Data.IORef+import Data.List (nub)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.Encoding qualified as TE+import Data.Time.Clock (NominalDiffTime, UTCTime, addUTCTime, getCurrentTime)+import GHC.Generics (Generic)+import Network.HTTP.Client qualified as HTTP+import Network.HTTP.Types (HeaderName, hAccept, hAuthorization, hContentType, parseQueryText, renderQueryText)+import Network.Socket qualified as Net+import Network.Socket.ByteString qualified as NetBS+import System.Timeout (timeout)++-- ---------------------------------------------------------------------------+-- Secrets++-- | A secret value. 'Show' prints only that it is redacted.+newtype Secret = Secret ByteString+ deriving stock (Eq)++instance Show Secret where+ show _ = "<redacted>"++secret :: ByteString -> Secret+secret = Secret++-- | The raw value, for the one place that must send it.+revealSecret :: Secret -> ByteString+revealSecret (Secret b) = b++-- | An operator-chosen name for a credential, such as @github-token@. Not+-- secret; resolved at the composition boundary.+newtype CredentialRef = CredentialRef {refName :: Text}+ deriving stock (Eq, Ord, Show, Generic)++newtype CredentialResolver = CredentialResolver {resolveCredential :: CredentialRef -> IO (Either Text Secret)}++-- ---------------------------------------------------------------------------+-- Static credentials++data StaticCredentials = StaticCredentials+ { -- | Sent as @Authorization: Bearer …@.+ bearer :: !(Maybe CredentialRef),+ -- | Custom headers such as an API key header.+ headers :: ![(HeaderName, CredentialRef)]+ }+ deriving stock (Eq, Show, Generic)++noStaticCredentials :: StaticCredentials+noStaticCredentials = StaticCredentials Nothing []++reservedCredentialHeader :: HeaderName -> Bool+reservedCredentialHeader n =+ isProtocolControlledHeader n || n `elem` [hAuthorization, "Proxy-Authorization", "Cookie", "Set-Cookie", "Origin"]++validHeaderName :: HeaderName -> Bool+validHeaderName n = not (BS.null o) && BS8.all tchar o+ where+ o = CI.original n+ tchar c = isAscii c && (isAlphaNum c || c `elem` ("!#$%&'*+-.^_`|~" :: String))++validHeaderValue :: ByteString -> Bool+validHeaderValue = BS.all (\w -> (w >= 0x20 && w /= 0x7f) || w == 0x09)++-- | A hook that adds the configured credentials, resolved on every send,+-- for requests to the endpoint's own origin only. Fails on a header name+-- that is invalid, duplicated, or one the client or the bearer mode owns.+staticCredentialHook :: Text -> CredentialResolver -> StaticCredentials -> Either Text McpRequestHook+staticCredentialHook endpointUrl resolver creds = do+ ep <- parseEndpoint endpointUrl+ forM_ creds.headers $ \(n, _) -> do+ unless (validHeaderName n) (Left ("invalid header name " <> TE.decodeUtf8Lenient (CI.original n)))+ when (reservedCredentialHeader n) (Left ("the header " <> TE.decodeUtf8Lenient (CI.original n) <> " cannot carry a configured credential"))+ let names = map fst creds.headers+ when (length (nub names) /= length names) (Left "a credential header is configured twice")+ Right . McpRequestHook $ \att ->+ if att.origin /= ep.origin+ then pure (SendDenied ("credentials are bound to " <> ep.origin))+ else do+ b <- traverse (resolveFor hAuthorization (\s -> "Bearer " <> s)) creds.bearer+ hs <- traverse (\(n, r) -> resolveFor n id r) creds.headers+ pure $ case sequence (maybe [] pure b <> hs) of+ Left why -> SendDenied why+ Right pairs -> SendAllowed [sendHeader n v | (n, v) <- pairs]+ where+ resolveFor n wrap r = do+ v <- resolver.resolveCredential r+ pure $ case v of+ Left why -> Left ("the credential " <> r.refName <> " could not be resolved: " <> Text.take 120 why)+ Right (Secret s)+ | BS.null s || not (validHeaderValue s) -> Left ("the credential " <> r.refName <> " is not a valid header value")+ | otherwise -> Right (n, wrap s)++-- ---------------------------------------------------------------------------+-- Challenges++-- | The parameters of a @Bearer@ challenge from @WWW-Authenticate@.+data AuthChallenge = AuthChallenge+ { resourceMetadata :: !(Maybe Text),+ scope :: ![Text],+ challengeError :: !(Maybe Text)+ }+ deriving stock (Eq, Show, Generic)++-- | Parse the @Bearer@ challenge. Other schemes are ignored.+parseChallenge :: Text -> Maybe AuthChallenge+parseChallenge raw = case dropWhile (not . isBearer) (schemes (Text.strip raw)) of+ (_ : params) ->+ let ps = takeWhile isParam params+ lookupP k = lookup k [(Text.toLower a, b) | Right (a, b) <- ps]+ in Just+ AuthChallenge+ { resourceMetadata = lookupP "resource_metadata",+ scope = maybe [] Text.words (lookupP "scope"),+ challengeError = lookupP "error"+ }+ [] -> Nothing+ where+ isBearer = \case+ Left s -> Text.toLower s == "bearer"+ Right _ -> False+ isParam = either (const False) (const True)+ schemes = tokenize++-- | Split a challenge list into scheme names (Left) and parameters (Right).+tokenize :: Text -> [Either Text (Text, Text)]+tokenize t0 = go (Text.stripStart t0)+ where+ go t+ | Text.null t = []+ | Just rest <- Text.stripPrefix "," t = go (Text.stripStart rest)+ | otherwise =+ let (word, rest) = Text.span (\c -> not (isSpace c) && c /= '=' && c /= ',') t+ rest' = Text.stripStart rest+ in case Text.uncons rest' of+ Just ('=', afterEq) ->+ let (val, remaining) = value (Text.stripStart afterEq)+ in Right (word, val) : go (Text.stripStart remaining)+ _ | Text.null word -> go (Text.drop 1 rest')+ _ -> Left word : go rest'+ value t = case Text.uncons t of+ Just ('"', rest) -> quoted rest ""+ _ -> Text.span (\c -> c /= ',' && not (isSpace c)) t+ quoted t acc = case Text.uncons t of+ Nothing -> (acc, "")+ Just ('\\', rest) -> case Text.uncons rest of+ Just (c, rest') -> quoted rest' (Text.snoc acc c)+ Nothing -> (acc, "")+ Just ('"', rest) -> (acc, rest)+ Just (c, rest) -> quoted rest (Text.snoc acc c)++-- ---------------------------------------------------------------------------+-- OAuth configuration++data ApplicationType = NativeApplication | WebApplication+ deriving stock (Eq, Show, Generic)++-- | Client credentials for one authorization server.+data ClientRegistration = ClientRegistration+ { clientId :: !Text,+ clientSecret :: !(Maybe Secret),+ -- | The issuer this registration belongs to.+ issuer :: !Text+ }+ deriving stock (Eq, Show, Generic)++-- | What the authorizer must present to the user.+data AuthorizationRequest = AuthorizationRequest+ { authorizationUrl :: !Text,+ redirectUri :: !Text,+ issuer :: !Text,+ scopes :: ![Text]+ }+ deriving stock (Eq, Show, Generic)++-- | The query parameters the authorization server redirected back with.+newtype AuthorizationCallback = AuthorizationCallback {callbackParams :: [(Text, Text)]}++instance Show AuthorizationCallback where+ show (AuthorizationCallback ps) = "AuthorizationCallback " <> show (map fst ps)++-- | Owns the user interaction: open the authorization URL and capture the+-- redirect. 'Left' when the user declined or the interaction failed.+newtype InteractiveAuthorizer = InteractiveAuthorizer+ { runAuthorization :: AuthorizationRequest -> IO (Either Text AuthorizationCallback)+ }++data OAuthConfig = OAuthConfig+ { -- | The MCP endpoint the tokens are for.+ endpoint :: !Text,+ -- | Whose grant this is; part of the storage key.+ principal :: !Text,+ -- | Where the authorization server redirects back to.+ redirectUri :: !Text,+ clientName :: !Text,+ applicationType :: !ApplicationType,+ -- | Credentials registered in advance, per issuer.+ preRegistered :: ![ClientRegistration],+ -- | An HTTPS URL of this client's metadata document, used when the+ -- authorization server supports Client ID Metadata Documents.+ clientMetadataDocument :: !(Maybe Text),+ -- | Permit deprecated dynamic client registration as a last resort.+ allowDynamicRegistration :: !Bool,+ -- | 'Nothing' for unattended hosts, which receive 'InteractionRequired'.+ authorizer :: !(Maybe InteractiveAuthorizer),+ -- | Allow plain HTTP for loopback hosts (development and tests).+ allowLoopbackHttp :: !Bool,+ -- | Deadline for each authorization-server request.+ requestTimeout :: !NominalDiffTime,+ -- | Refresh an access token this long before it expires.+ refreshSkew :: !NominalDiffTime+ }++oauthConfig :: Text -> Text -> Text -> OAuthConfig+oauthConfig ep who redirect =+ OAuthConfig+ { endpoint = ep,+ principal = who,+ redirectUri = redirect,+ clientName = "baikai-mcp",+ applicationType = NativeApplication,+ preRegistered = [],+ clientMetadataDocument = Nothing,+ allowDynamicRegistration = False,+ authorizer = Nothing,+ allowLoopbackHttp = True,+ requestTimeout = 30,+ refreshSkew = 30+ }++-- ---------------------------------------------------------------------------+-- Token storage++data TokenSet = TokenSet+ { accessToken :: !Secret,+ refreshToken :: !(Maybe Secret),+ expiresAt :: !(Maybe UTCTime),+ grantedScopes :: ![Text]+ }+ deriving stock (Eq, Show, Generic)++-- | A grant, bound to the authorization server and client that issued it.+data StoredGrant = StoredGrant+ { issuer :: !Text,+ clientId :: !Text,+ resource :: !Text,+ tokens :: !TokenSet+ }+ deriving stock (Eq, Show, Generic)++-- | Pluggable storage. Grants are keyed by principal and resource;+-- registrations by issuer.+data TokenStore = TokenStore+ { loadGrant :: Text -> Text -> IO (Maybe StoredGrant),+ saveGrant :: Text -> Text -> StoredGrant -> IO (),+ deleteGrant :: Text -> Text -> IO (),+ loadRegistration :: Text -> IO (Maybe ClientRegistration),+ saveRegistration :: ClientRegistration -> IO ()+ }++newInMemoryTokenStore :: IO TokenStore+newInMemoryTokenStore = do+ grants <- newIORef (Map.empty :: Map (Text, Text) StoredGrant)+ regs <- newIORef (Map.empty :: Map Text ClientRegistration)+ pure+ TokenStore+ { loadGrant = \p r -> Map.lookup (p, r) <$> readIORef grants,+ saveGrant = \p r g -> atomicModifyIORef' grants (\m -> (Map.insert (p, r) g m, ())),+ deleteGrant = \p r -> atomicModifyIORef' grants (\m -> (Map.delete (p, r) m, ())),+ loadRegistration = \i -> Map.lookup i <$> readIORef regs,+ saveRegistration = \reg -> atomicModifyIORef' regs (\m -> (Map.insert reg.issuer reg m, ()))+ }++-- ---------------------------------------------------------------------------+-- Errors and outcomes++data AuthError+ = AuthConfigInvalid !Text+ | -- | A destination was refused (scheme, origin) before any request.+ AuthDestinationRefused !Text+ | AuthMetadataUnavailable !Text+ | -- | Protected resource metadata names a different resource.+ AuthWrongResource !Text+ | -- | Authorization server metadata does not carry the issuer it was+ -- fetched for.+ AuthIssuerMismatch !Text+ | AuthPkceUnsupported+ | AuthNoRegistration !Text+ | AuthRegistrationFailed !Text+ | -- | The redirect's @state@ is not the one this flow issued.+ AuthStateMismatch+ | -- | The redirect's @iss@ is missing or names another issuer. The+ -- response's error fields were not read.+ AuthCallbackIssuerMismatch+ | -- | The user or the authorization server declined.+ AuthDeclined !Text+ | AuthTokenRequestFailed !Text+ | AuthTransport !Text+ deriving stock (Eq, Show, Generic)++data AuthOutcome+ = -- | Tokens are stored; retry the operation once.+ Authorized+ | -- | A user must authorize, but this host has no authorizer.+ InteractionRequired !AuthorizationRequest+ | -- | The server needs scopes beyond the grant. Granting them requires+ -- explicit consent: call 'authorizeFromChallenge' with the wider set.+ InsufficientScope ![Text]+ | -- | The server refused the credential and no recovery applies.+ AccessDenied !Text+ deriving stock (Eq, Show, Generic)++-- ---------------------------------------------------------------------------+-- The provider++data AsMetadata = AsMetadata+ { issuer :: !Text,+ authorizationEndpoint :: !Text,+ tokenEndpoint :: !Text,+ registrationEndpoint :: !(Maybe Text),+ issParameterSupported :: !Bool,+ cimdSupported :: !Bool,+ tokenAuthMethods :: ![Text]+ }++data OAuthProvider = OAuthProvider+ { config :: !OAuthConfig,+ store :: !TokenStore,+ manager :: !HTTP.Manager,+ resource :: !Text,+ resourceOrigin :: !Text,+ endpoint :: !HttpEndpoint,+ asCache :: !(IORef (Map Text AsMetadata)),+ lock :: !(MVar ())+ }++-- | Build a provider for one endpoint and principal.+newOAuthProvider :: HTTP.Manager -> TokenStore -> OAuthConfig -> IO (Either AuthError OAuthProvider)+newOAuthProvider mgr st cfg = case parseEndpoint cfg.endpoint of+ Left why -> pure (Left (AuthConfigInvalid why))+ Right ep -> case canonicalResource cfg.endpoint of+ Nothing -> pure (Left (AuthConfigInvalid "the endpoint has no canonical resource URI"))+ Just res -> do+ cache <- newIORef Map.empty+ l <- newMVar ()+ pure (Right OAuthProvider {config = cfg, store = st, manager = mgr, resource = res, resourceOrigin = ep.origin, endpoint = ep, asCache = cache, lock = l})++-- | The canonical resource URI (RFC 8707): lower-cased scheme and host,+-- the port only when not the default, the path without a trailing slash,+-- and no query or fragment.+canonicalResource :: Text -> Maybe Text+canonicalResource raw = case parseEndpoint raw of+ Left _ -> Nothing+ Right ep ->+ let defaultPort = if ep.scheme == "https" then 443 else 80+ portPart = if ep.port == defaultPort then "" else ":" <> Text.pack (show ep.port)+ rawPath = Text.takeWhile (\c -> c /= '?' && c /= '#') (snd (Text.breakOn "/" (Text.drop (Text.length ep.scheme + 3) (Text.strip raw))))+ path = if rawPath == "/" then "" else fromMaybe rawPath (Text.stripSuffix "/" rawPath)+ in Just (ep.scheme <> "://" <> ep.host <> portPart <> path)++-- | The client hook: a current access token for the provider's resource+-- origin, refreshed first if it is about to expire. Without a grant the+-- request goes out anonymously so that the server can issue its challenge.+oauthRequestHook :: OAuthProvider -> McpRequestHook+oauthRequestHook p = McpRequestHook $ \att ->+ if att.origin /= p.resourceOrigin+ then pure (SendDenied ("credentials are bound to " <> p.resourceOrigin))+ else do+ r <- currentAccessToken p+ pure $ case r of+ Left why -> SendDenied why+ Right Nothing -> SendAllowed []+ Right (Just (Secret tok)) -> SendAllowed [sendHeader hAuthorization ("Bearer " <> tok)]++-- | The stored access token, refreshing it under the provider's lock.+currentAccessToken :: OAuthProvider -> IO (Either Text (Maybe Secret))+currentAccessToken p = withMVar p.lock $ \_ -> do+ g <- p.store.loadGrant p.config.principal p.resource+ case g of+ Nothing -> pure (Right Nothing)+ Just grant -> do+ now <- getCurrentTime+ let fresh = maybe True (\t -> addUTCTime p.config.refreshSkew now < t) grant.tokens.expiresAt+ if fresh+ then pure (Right (Just grant.tokens.accessToken))+ else case grant.tokens.refreshToken of+ Nothing -> do+ p.store.deleteGrant p.config.principal p.resource+ pure (Right Nothing)+ Just rt -> do+ r <- refreshGrant p grant rt+ case r of+ Right g' -> pure (Right (Just g'.tokens.accessToken))+ Left (AuthTokenRequestFailed "invalid_grant") -> do+ p.store.deleteGrant p.config.principal p.resource+ pure (Right Nothing)+ Left e -> pure (Left ("refreshing the access token failed: " <> renderAuthError e))++renderAuthError :: AuthError -> Text+renderAuthError = Text.take 200 . Text.pack . show++-- | Refresh and store atomically: the new set replaces the old only after+-- a complete, valid response. A rotated refresh token replaces the old.+refreshGrant :: OAuthProvider -> StoredGrant -> Secret -> IO (Either AuthError StoredGrant)+refreshGrant p grant (Secret rt) = do+ md <- asMetadata p grant.issuer+ case md of+ Left e -> pure (Left e)+ Right meta -> do+ reg <- registrationFor p meta+ case reg of+ Left e -> pure (Left e)+ Right client+ | client.clientId /= grant.clientId -> pure (Left (AuthNoRegistration "the stored grant belongs to another client"))+ | otherwise -> do+ r <-+ tokenRequest p meta client $+ [ ("grant_type", "refresh_token"),+ ("refresh_token", TE.decodeUtf8 rt),+ ("resource", p.resource)+ ]+ case r of+ Left e -> pure (Left e)+ Right ts -> do+ let ts' = ts {refreshToken = maybe grant.tokens.refreshToken Just ts.refreshToken, grantedScopes = if null ts.grantedScopes then grant.tokens.grantedScopes else ts.grantedScopes}+ g' = grant {tokens = ts'}+ p.store.saveGrant p.config.principal p.resource g'+ pure (Right g')++-- | After a refused MCP request: refresh once if possible (the host then+-- retries once), report an insufficient scope, or report that a fresh+-- authorization is needed.+recoverFromChallenge :: OAuthProvider -> McpError -> IO (Either AuthError AuthOutcome)+recoverFromChallenge p e = case (e.httpStatus, e.challenge >>= parseChallenge) of+ (Just 403, Just ch) | ch.challengeError == Just "insufficient_scope" -> pure (Right (InsufficientScope ch.scope))+ (Just 403, _) -> pure (Right (AccessDenied "the server refused the credential"))+ (Just 401, _) -> withMVar p.lock $ \_ -> do+ g <- p.store.loadGrant p.config.principal p.resource+ case g >>= \grant -> (grant,) <$> grant.tokens.refreshToken of+ Just (grant, rt) -> do+ r <- refreshGrant p grant rt+ case r of+ Right _ -> pure (Right Authorized)+ Left (AuthTokenRequestFailed "invalid_grant") -> do+ p.store.deleteGrant p.config.principal p.resource+ pure (Right (AccessDenied "the grant was revoked; authorize again"))+ Left err -> pure (Left err)+ Nothing -> do+ forM_ g $ \_ -> p.store.deleteGrant p.config.principal p.resource+ pure (Right (AccessDenied "no refreshable grant; authorize again"))+ _ -> pure (Right (AccessDenied "the failure is not an authorization challenge"))++-- | Run the authorization flow for a 401 (or an explicit scope upgrade).+-- Discovers the authorization server from the challenge, registers if+-- needed, asks the authorizer, validates the redirect and redeems the+-- code. Scopes: the challenge's, else the resource's advertised scopes,+-- plus any scopes passed explicitly (for a consented step-up).+authorizeFromChallenge :: OAuthProvider -> Maybe Text -> [Text] -> IO (Either AuthError AuthOutcome)+authorizeFromChallenge p rawChallenge extraScopes = do+ let ch = rawChallenge >>= parseChallenge+ prm <- protectedResourceMetadata p (ch >>= (.resourceMetadata))+ case prm of+ Left e -> pure (Left e)+ Right (servers, supported) -> case servers of+ [] -> pure (Left (AuthMetadataUnavailable "the protected resource names no authorization server"))+ (iss : _) -> do+ md <- asMetadata p iss+ case md of+ Left e -> pure (Left e)+ Right meta -> do+ reg <- registrationFor p meta+ case reg of+ Left e -> pure (Left e)+ Right client -> do+ previous <- p.store.loadGrant p.config.principal p.resource+ let challenged = maybe [] (.scope) ch+ base = if null challenged then supported else challenged+ carried = maybe [] (\g -> if g.issuer == meta.issuer then g.tokens.grantedScopes else []) previous+ scopes = nub (base <> carried <> extraScopes)+ runFlow p meta client scopes++runFlow :: OAuthProvider -> AsMetadata -> ClientRegistration -> [Text] -> IO (Either AuthError AuthOutcome)+runFlow p meta client scopes = do+ verifier <- randomToken+ st <- randomToken+ let challenge = pkceChallenge verifier+ query =+ [ ("response_type", Just "code"),+ ("client_id", Just client.clientId),+ ("redirect_uri", Just p.config.redirectUri),+ ("code_challenge", Just challenge),+ ("code_challenge_method", Just "S256"),+ ("state", Just st),+ ("resource", Just p.resource)+ ]+ <> [("scope", Just (Text.unwords scopes)) | not (null scopes)]+ sep = if Text.isInfixOf "?" meta.authorizationEndpoint then "&" else "?"+ url = meta.authorizationEndpoint <> sep <> TE.decodeUtf8 (BS.drop 1 (toStrictBuilder (renderQueryText True query)))+ req = AuthorizationRequest {authorizationUrl = url, redirectUri = p.config.redirectUri, issuer = meta.issuer, scopes = scopes}+ case p.config.authorizer of+ Nothing -> pure (Right (InteractionRequired req))+ Just authz -> do+ cb <- authz.runAuthorization req+ case cb of+ Left why -> pure (Left (AuthDeclined (Text.take 200 why)))+ Right callback -> case validateCallback meta.issParameterSupported meta.issuer st callback of+ Left e -> pure (Left e)+ Right code -> do+ r <-+ tokenRequest p meta client $+ [ ("grant_type", "authorization_code"),+ ("code", code),+ ("redirect_uri", p.config.redirectUri),+ ("code_verifier", verifier),+ ("resource", p.resource)+ ]+ case r of+ Left e -> pure (Left e)+ Right ts -> do+ let ts' = ts {grantedScopes = if null ts.grantedScopes then scopes else ts.grantedScopes}+ withMVar p.lock $ \_ ->+ p.store.saveGrant p.config.principal p.resource StoredGrant {issuer = meta.issuer, clientId = client.clientId, resource = p.resource, tokens = ts'}+ pure (Right Authorized)+ where+ toStrictBuilder = BS.toStrict . builderToLazy++-- | RFC 9207 validation, then state, before anything else is read.+validateCallback :: Bool -> Text -> Text -> AuthorizationCallback -> Either AuthError Text+validateCallback issSupported expectedIssuer expectedState (AuthorizationCallback ps) = do+ let get k = lookup k ps+ case (issSupported, get "iss") of+ (_, Just i) | i /= expectedIssuer -> Left AuthCallbackIssuerMismatch+ (True, Nothing) -> Left AuthCallbackIssuerMismatch+ _ -> Right ()+ unless (get "state" == Just expectedState) (Left AuthStateMismatch)+ case get "error" of+ Just e -> Left (AuthDeclined (Text.take 64 e))+ Nothing -> pure ()+ maybe (Left (AuthDeclined "the redirect carried no authorization code")) Right (get "code")++-- | @BASE64URL(SHA256(verifier))@.+pkceChallenge :: Text -> Text+pkceChallenge v = TE.decodeUtf8 (B64URL.encodeUnpadded (BA.convert (hashWith SHA256 (TE.encodeUtf8 v))))++randomToken :: IO Text+randomToken = TE.decodeUtf8 . B64URL.encodeUnpadded <$> (getRandomBytes 32 :: IO ByteString)++-- ---------------------------------------------------------------------------+-- Discovery++-- | Fetch protected resource metadata: from the challenge's URL, else the+-- path-inserted well-known URL, else the root one. Its @resource@ must be+-- this endpoint's canonical resource.+protectedResourceMetadata :: OAuthProvider -> Maybe Text -> IO (Either AuthError ([Text], [Text]))+protectedResourceMetadata p fromHeader = do+ let base = p.endpoint.origin+ path = case canonicalResource p.config.endpoint >>= Text.stripPrefix (originPrefix p) of+ Just pth | not (Text.null pth) -> pth+ _ -> ""+ candidates = case fromHeader of+ Just u -> [u]+ Nothing -> [wellKnown base ("/.well-known/oauth-protected-resource" <> path) | not (Text.null path)] <> [wellKnown base "/.well-known/oauth-protected-resource"]+ tryEach candidates+ where+ tryEach [] = pure (Left (AuthMetadataUnavailable "no protected resource metadata was found"))+ tryEach (u : us) = do+ r <- getJson p u+ case r of+ Right (Object o) -> pure (validatePrm o)+ Right _ -> pure (Left (AuthMetadataUnavailable "protected resource metadata is not an object"))+ Left (AuthMetadataUnavailable _) -> tryEach us+ Left e -> pure (Left e)+ validatePrm o = do+ res <- case KeyMap.lookup "resource" o of+ Just (String r) -> Right r+ _ -> Left (AuthMetadataUnavailable "protected resource metadata has no resource")+ unless (canonicalResource res == Just p.resource) (Left (AuthWrongResource (Text.take 120 res)))+ servers <- case KeyMap.lookup "authorization_servers" o of+ Just (Array xs) -> Right [s | String s <- foldr (:) [] xs]+ _ -> Left (AuthMetadataUnavailable "protected resource metadata lists no authorization servers")+ let supported = case KeyMap.lookup "scopes_supported" o of+ Just (Array xs) -> [s | String s <- foldr (:) [] xs]+ _ -> []+ Right (servers, supported)++originPrefix :: OAuthProvider -> Text+originPrefix p = p.endpoint.scheme <> "://" <> Text.takeWhile (/= '/') (Text.drop (Text.length p.endpoint.scheme + 3) p.resource)++wellKnown :: Text -> Text -> Text+wellKnown origin path =+ -- origin is scheme://host:port; render without a default port.+ let (sch, rest) = Text.breakOn "://" origin+ hostPort = Text.drop 3 rest+ shown = case Text.stripSuffix (if sch == "https" then ":443" else ":80") hostPort of+ Just h -> h+ Nothing -> hostPort+ in sch <> "://" <> shown <> path++-- | Authorization server metadata, tried at the RFC 8414 and OpenID+-- Connect locations in the specified order, accepted only when its+-- @issuer@ is identical to the one requested and it supports PKCE S256.+asMetadata :: OAuthProvider -> Text -> IO (Either AuthError AsMetadata)+asMetadata p iss = do+ cached <- Map.lookup iss <$> readIORef p.asCache+ case cached of+ Just m -> pure (Right m)+ Nothing -> case parseEndpoint iss of+ Left _ -> pure (Left (AuthConfigInvalid "the authorization server issuer is not a URL"))+ Right iep -> do+ let path = let ip = issuerPath iss in fromMaybe ip (Text.stripSuffix "/" ip)+ root = wellKnown iep.origin+ candidates+ | Text.null path = [root "/.well-known/oauth-authorization-server", root "/.well-known/openid-configuration"]+ | otherwise =+ [ root ("/.well-known/oauth-authorization-server" <> path),+ root ("/.well-known/openid-configuration" <> path),+ root (path <> "/.well-known/openid-configuration")+ ]+ r <- tryEach candidates+ case r of+ Right m -> atomicModifyIORef' p.asCache (\c -> (Map.insert iss m c, ())) >> pure (Right m)+ Left e -> pure (Left e)+ where+ issuerPath i = let afterScheme = Text.drop 3 (snd (Text.breakOn "://" i)) in snd (Text.breakOn "/" afterScheme)+ tryEach [] = pure (Left (AuthMetadataUnavailable "no authorization server metadata was found"))+ tryEach (u : us) = do+ r <- getJson p u+ case r of+ Right (Object o) -> pure (validate o)+ Right _ -> pure (Left (AuthMetadataUnavailable "authorization server metadata is not an object"))+ Left (AuthMetadataUnavailable _) -> tryEach us+ Left e -> pure (Left e)+ validate o = do+ let str k = case KeyMap.lookup k o of+ Just (String s) -> Just s+ _ -> Nothing+ strs k = case KeyMap.lookup k o of+ Just (Array xs) -> [s | String s <- foldr (:) [] xs]+ _ -> []+ flag k = KeyMap.lookup k o == Just (Bool True)+ unless (str "issuer" == Just iss) (Left (AuthIssuerMismatch (Text.take 120 (fromMaybe "" (str "issuer")))))+ unless ("S256" `elem` strs "code_challenge_methods_supported") (Left AuthPkceUnsupported)+ authz <- maybe (Left (AuthMetadataUnavailable "no authorization_endpoint")) Right (str "authorization_endpoint")+ tok <- maybe (Left (AuthMetadataUnavailable "no token_endpoint")) Right (str "token_endpoint")+ mapM_ (destinationOk p) ([authz, tok] <> maybe [] pure (str "registration_endpoint"))+ Right+ AsMetadata+ { issuer = iss,+ authorizationEndpoint = authz,+ tokenEndpoint = tok,+ registrationEndpoint = str "registration_endpoint",+ issParameterSupported = flag "authorization_response_iss_parameter_supported",+ cimdSupported = flag "client_id_metadata_document_supported",+ tokenAuthMethods = strs "token_endpoint_auth_methods_supported"+ }++-- | HTTPS, or HTTP to a loopback host when allowed.+destinationOk :: OAuthProvider -> Text -> Either AuthError ()+destinationOk p u = case parseEndpoint u of+ Left _ -> Left (AuthDestinationRefused (Text.take 120 u))+ Right ep+ | ep.scheme == "https" -> Right ()+ | p.config.allowLoopbackHttp && ep.host `elem` ["127.0.0.1", "localhost", "[::1]"] -> Right ()+ | otherwise -> Left (AuthDestinationRefused ("authorization endpoints must use HTTPS: " <> ep.rendered))++-- | Pre-registered, then Client ID Metadata Document, then (when allowed)+-- dynamic registration. Registrations are keyed by issuer and never+-- reused for another.+registrationFor :: OAuthProvider -> AsMetadata -> IO (Either AuthError ClientRegistration)+registrationFor p meta = case [r | r <- p.config.preRegistered, r.issuer == meta.issuer] of+ (r : _) -> pure (Right r)+ [] -> case p.config.clientMetadataDocument of+ Just doc | meta.cimdSupported -> pure (Right ClientRegistration {clientId = doc, clientSecret = Nothing, issuer = meta.issuer})+ _ -> do+ stored <- p.store.loadRegistration meta.issuer+ case stored of+ Just r | r.issuer == meta.issuer -> pure (Right r)+ _ -> case meta.registrationEndpoint of+ Just regUrl | p.config.allowDynamicRegistration -> dynamicRegistration p meta regUrl+ _ -> pure (Left (AuthNoRegistration ("no client registration is available for " <> meta.issuer <> "; pre-register a client or host a client metadata document")))++dynamicRegistration :: OAuthProvider -> AsMetadata -> Text -> IO (Either AuthError ClientRegistration)+dynamicRegistration p meta regUrl = do+ let body =+ object+ [ "client_name" .= p.config.clientName,+ "redirect_uris" .= [p.config.redirectUri],+ "grant_types" .= ["authorization_code", "refresh_token" :: Text],+ "response_types" .= ["code" :: Text],+ "token_endpoint_auth_method" .= ("none" :: Text),+ "application_type" .= (case p.config.applicationType of NativeApplication -> "native" :: Text; WebApplication -> "web")+ ]+ r <- sendJson p "POST" regUrl [(hContentType, "application/json")] (BS.toStrict (Aeson.encode body))+ case r of+ Left e -> pure (Left e)+ Right (st, v)+ | st >= 200 && st < 300,+ Object o <- v,+ Just (String cid) <- KeyMap.lookup "client_id" o -> do+ let reg = ClientRegistration {clientId = cid, clientSecret = case KeyMap.lookup "client_secret" o of Just (String s) -> Just (Secret (TE.encodeUtf8 s)); _ -> Nothing, issuer = meta.issuer}+ p.store.saveRegistration reg+ pure (Right reg)+ | otherwise -> pure (Left (AuthRegistrationFailed ("the registration endpoint answered HTTP " <> Text.pack (show st))))++-- ---------------------------------------------------------------------------+-- Token endpoint++tokenRequest :: OAuthProvider -> AsMetadata -> ClientRegistration -> [(Text, Text)] -> IO (Either AuthError TokenSet)+tokenRequest p meta client params = do+ let (authHeaders, clientParams) = case client.clientSecret of+ Nothing -> ([], [("client_id", client.clientId)])+ Just (Secret s)+ | null meta.tokenAuthMethods || "client_secret_basic" `elem` meta.tokenAuthMethods ->+ ([(hAuthorization, "Basic " <> B64.encode (TE.encodeUtf8 (formEncode client.clientId) <> ":" <> TE.encodeUtf8 (formEncode (TE.decodeUtf8 s))))], [])+ | otherwise -> ([], [("client_id", client.clientId), ("client_secret", TE.decodeUtf8 s)])+ form = renderForm (params <> clientParams)+ r <- sendJson p "POST" meta.tokenEndpoint ((hContentType, "application/x-www-form-urlencoded") : authHeaders) form+ now <- getCurrentTime+ pure $ case r of+ Left e -> Left e+ Right (st, Object o)+ | st >= 200 && st < 300 -> do+ tok <- case KeyMap.lookup "access_token" o of+ Just (String t) | not (Text.null t) -> Right t+ _ -> Left (AuthTokenRequestFailed "the token response has no access_token")+ case KeyMap.lookup "token_type" o of+ Just (String t) | Text.toLower t == "bearer" -> Right ()+ _ -> Left (AuthTokenRequestFailed "the token response is not a bearer token")+ let expires = case KeyMap.lookup "expires_in" o of+ Just (Number n) -> Just (addUTCTime (realToFrac n) now)+ _ -> Nothing+ refresh = case KeyMap.lookup "refresh_token" o of+ Just (String t) | not (Text.null t) -> Just (Secret (TE.encodeUtf8 t))+ _ -> Nothing+ granted = case KeyMap.lookup "scope" o of+ Just (String s) -> Text.words s+ _ -> []+ Right TokenSet {accessToken = Secret (TE.encodeUtf8 tok), refreshToken = refresh, expiresAt = expires, grantedScopes = granted}+ | otherwise -> Left (AuthTokenRequestFailed (oauthErrorCode o))+ Right (st, _) -> Left (AuthTokenRequestFailed ("the token endpoint answered HTTP " <> Text.pack (show st)))+ where+ oauthErrorCode o = case KeyMap.lookup "error" o of+ Just (String e) | Text.all (\c -> isAscii c && (isAlphaNum c || c == '_')) e -> Text.take 64 e+ _ -> "token_request_rejected"++formEncode :: Text -> Text+formEncode t = TE.decodeUtf8 (BS.drop 1 (BS.toStrict (builderToLazy (renderQueryText False [("", Just t)]))))++renderForm :: [(Text, Text)] -> ByteString+renderForm ps = BS.toStrict (builderToLazy (renderQueryText False [(k, Just v) | (k, v) <- ps]))++-- ---------------------------------------------------------------------------+-- HTTP to authorization servers++getJson :: OAuthProvider -> Text -> IO (Either AuthError Value)+getJson p u = do+ r <- sendJson p "GET" u [] BS.empty+ pure $ case r of+ Left e -> Left e+ Right (st, v)+ | st >= 200 && st < 300 -> Right v+ | otherwise -> Left (AuthMetadataUnavailable ("HTTP " <> Text.pack (show st) <> " from " <> Text.take 120 u))++-- | One bounded request with no redirects to a validated destination.+sendJson :: OAuthProvider -> ByteString -> Text -> [(HeaderName, ByteString)] -> ByteString -> IO (Either AuthError (Int, Value))+sendJson p method u hdrs body = case destinationOk p u of+ Left e -> pure (Left e)+ Right () -> case HTTP.parseRequest @(Either SomeException) (Text.unpack u) of+ Left _ -> pure (Left (AuthDestinationRefused (Text.take 120 u)))+ Right base -> do+ let req =+ base+ { HTTP.method = method,+ HTTP.redirectCount = 0,+ HTTP.checkResponse = \_ _ -> pure (),+ HTTP.responseTimeout = HTTP.responseTimeoutNone,+ HTTP.requestHeaders = (hAccept, "application/json") : hdrs,+ HTTP.requestBody = HTTP.RequestBodyBS body+ }+ micros = max 1 (floor (realToFrac p.config.requestTimeout * 1000000 :: Double))+ r <- try @SomeException (timeout micros (HTTP.withResponse req p.manager (\resp -> (statusOf resp,) <$> readBounded 1048576 (HTTP.responseBody resp))))+ case r of+ Left e -> rethrowAsync e >> pure (Left (AuthTransport "the authorization server could not be reached"))+ Right Nothing -> pure (Left (AuthTransport "the authorization server did not answer in time"))+ Right (Just (_, Left _)) -> pure (Left (AuthTransport "the authorization server's response is too large"))+ Right (Just (st, Right bytes))+ | BS.null bytes -> pure (Right (st, Null))+ | otherwise -> pure (Right (st, fromMaybe Null (Aeson.decodeStrict bytes)))++-- ---------------------------------------------------------------------------+-- Loopback authorizer++data LoopbackConfig = LoopbackConfig+ { -- | Port on 127.0.0.1 named by the registered redirect URI.+ port :: !Int,+ callbackPath :: !Text,+ -- | Open the authorization URL (in a browser, or by printing it).+ present :: AuthorizationRequest -> IO (),+ -- | How long to wait for the redirect.+ waitFor :: !NominalDiffTime+ }++-- | Present the request, then accept one redirect on @127.0.0.1@ within+-- the deadline. The listener is closed on return, timeout or exception.+loopbackAuthorizer :: LoopbackConfig -> InteractiveAuthorizer+loopbackAuthorizer lc = InteractiveAuthorizer $ \req ->+ bracket openListener Net.close $ \sock -> do+ lc.present req+ r <- timeout (max 1 (floor (realToFrac lc.waitFor * 1000000 :: Double))) (acceptCallback sock)+ pure (fromMaybe (Left "no authorization redirect arrived in time") r)+ where+ openListener = do+ sock <- Net.socket Net.AF_INET Net.Stream Net.defaultProtocol+ Net.setSocketOption sock Net.ReuseAddr 1+ Net.bind sock (Net.SockAddrInet (fromIntegral lc.port) (Net.tupleToHostAddress (127, 0, 0, 1)))+ Net.listen sock 4+ pure sock+ acceptCallback sock = do+ (conn, _) <- Net.accept sock+ bracket (pure conn) Net.close $ \c -> do+ reqLine <- readRequestHead c BS.empty+ let target = case BS8.words (BS8.takeWhile (/= '\r') reqLine) of+ (_ : t : _) -> t+ _ -> ""+ (path, query) = BS8.break (== '?') target+ params = [(k, fromMaybe "" v) | (k, v) <- parseQueryText (BS.drop 1 query)]+ NetBS.sendAll c "HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\nAuthorization received. You can close this window.\n"+ if TE.decodeUtf8Lenient path /= lc.callbackPath+ then acceptCallback sock+ else pure (Right (AuthorizationCallback params))+ readRequestHead c acc+ | BS.length acc > 16384 = pure acc+ | "\r\n\r\n" `BS.isInfixOf` acc = pure acc+ | otherwise = do+ chunk <- NetBS.recv c 4096+ if BS.null chunk then pure acc else readRequestHead c (acc <> chunk)++builderToLazy :: Builder.Builder -> LBS.ByteString+builderToLazy = Builder.toLazyByteString
+ src/Baikai/Mcp/Client.hs view
@@ -0,0 +1,993 @@+-- | A Model Context Protocol client handle.+--+-- An 'McpConnection' is a /local/ resource: it owns the binding to one+-- server endpoint, the protocol era detected when it was opened, the host's+-- request hook, its limits and, for handshake-era servers only, the session+-- the server issued. Modern MCP (@2026-07-28@) has no handshake and no+-- session; each request carries its own version and capabilities. See+-- @docs/adr/0031-remote-mcp-connections-are-local-client-handles.md@.+--+-- Every actual transmission — discovery, a compatibility probe, the+-- handshake, each page, each continuation round, a reply to a legacy+-- server's ping and the session teardown — first passes the+-- 'McpRequestHook'. The hook can refuse the send, in which case nothing is+-- transmitted, or add headers such as credentials.+--+-- A reply that is lost leaves the remote effect unknown. Such a failure is+-- reported with 'Uncertain' delivery and is never replayed here.+module Baikai.Mcp.Client+ ( -- * Configuration+ McpServerConfig (..),+ mcpServerConfig,+ McpProfile (..),+ McpLimits (..),+ defaultMcpLimits,+ defaultClientInfo,++ -- * Request hook+ McpRequestHook (..),+ SendAttempt (..),+ AttemptPurpose (..),+ SendDecision (..),+ SendHeader,+ sendHeader,+ sendHeaderName,+ denyAll,++ -- * Lifecycle+ McpConnection,+ connectMcp,+ connectMcpWith,+ closeMcp,+ withMcpConnection,+ connectionDescription,+ connectionEra,+ connectionServerName,+ connectionBindingShape,+ BindingShape (..),+ connectionOpenListeners,++ -- * Requests+ McpCall (..),+ mcpCall,+ CompleteResult (..),+ McpOutcome (..),+ Unfinished (..),+ UnfinishedReason (..),+ callMethod,+ callInteractive,++ -- * Pages+ requestPage,++ -- * Subscriptions+ Subscription,+ subscriptionId,+ subscriptionRequested,+ subscriptionAcknowledged,+ SubscriptionEvent (..),+ SubscriptionEnd (..),+ withSubscription,+ nextSubscriptionEvent,++ -- * Errors+ module Baikai.Mcp.Error,++ -- * Caller-owned streams (stdio)+ McpStreamConfig (..),+ mcpStreamConfig,+ StreamProfile (..),+ connectMcpStream,+ withMcpStream,++ -- * Internal construction (for transports in this package)+ connectWithBinding,+ ConnectPlan (..),+ )+where++import Baikai.Mcp.Error+import Baikai.Mcp.Internal.Binding+import Baikai.Mcp.Internal.Http (HttpEndpoint, parseEndpoint, rethrowAsync)+import Baikai.Mcp.Protocol+import Baikai.Mcp.Transport+import Baikai.Mcp.Transport.HttpSse (openHttpSseBinding)+import Baikai.Mcp.Transport.Stream (McpStream, streamBinding)+import Control.Exception (SomeException, bracket, mask, onException, try)+import Control.Monad (forM_, unless, void)+import Data.Aeson (Value (..), toJSON)+import Data.Aeson qualified as Aeson+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Object, Parser, parseEither)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.IORef+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe, isJust)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.Encoding qualified as TE+import Data.Time.Clock (NominalDiffTime)+import Data.Version (showVersion)+import GHC.Generics (Generic)+import Network.HTTP.Client qualified as HTTP+import Network.HTTP.Client.TLS qualified as TLS+import Network.HTTP.Types (Header, HeaderName)+import Paths_baikai_mcp qualified as Paths+import System.Timeout (timeout)++-- ---------------------------------------------------------------------------+-- Configuration++-- | How the client chooses a protocol era and transport.+data McpProfile+ = -- | Probe with @server/discover@; fall back to the handshake-era+ -- Streamable HTTP revision only when the probe's answer carries no+ -- recognized modern error. Credential challenges, network failures and+ -- malformed successes never cause a fallback.+ McpAuto+ | -- | Modern revisions only; a legacy server is an incompatibility.+ McpModernOnly+ | -- | A known handshake-era Streamable HTTP server; skip the probe.+ McpLegacyStreamableHttp+ | -- | The deprecated @2024-11-05@ HTTP+SSE transport, selected+ -- explicitly. Eligible for removal from the protocol; see+ -- "Baikai.Mcp.Transport.HttpSse".+ McpLegacyHttpSse+ deriving stock (Eq, Show, Generic)++-- | Finite ceilings for every operation.+data McpLimits = McpLimits+ { -- | Bytes in one reply.+ maxResponseBytes :: !Int,+ -- | Bytes in one SSE event or line.+ maxFrameBytes :: !Int,+ -- | Deadline for one operation, including its continuation rounds.+ requestTimeout :: !NominalDiffTime,+ -- | Deadline for opening a connection (probe and handshake).+ connectTimeout :: !NominalDiffTime,+ -- | How many times a state-only interim result is continued. Zero+ -- disables continuation.+ maxContinuationRounds :: !Int+ }+ deriving stock (Eq, Show, Generic)++defaultMcpLimits :: McpLimits+defaultMcpLimits =+ McpLimits+ { maxResponseBytes = 16 * 1024 * 1024,+ maxFrameBytes = 4 * 1024 * 1024,+ requestTimeout = 60,+ connectTimeout = 30,+ maxContinuationRounds = 4+ }++data McpServerConfig = McpServerConfig+ { -- | A non-secret identity for the server, shown to the request hook.+ serverName :: !Text,+ -- | The MCP endpoint URL. Must not embed credentials.+ endpoint :: !Text,+ profile :: !McpProfile,+ limits :: !McpLimits,+ requestHook :: !McpRequestHook,+ -- | Sent as @clientInfo@; 'Nothing' omits it on modern requests.+ clientInfo :: !(Maybe Implementation)+ }++-- | A configuration with the automatic profile, default limits, no+-- credentials and every request allowed.+mcpServerConfig :: Text -> Text -> McpServerConfig+mcpServerConfig nm url =+ McpServerConfig+ { serverName = nm,+ endpoint = url,+ profile = McpAuto,+ limits = defaultMcpLimits,+ requestHook = mempty,+ clientInfo = Just defaultClientInfo+ }++defaultClientInfo :: Implementation+defaultClientInfo = implementation "baikai-mcp" (Text.pack (showVersion Paths.version))++-- ---------------------------------------------------------------------------+-- Request hook++-- | Why a transmission is about to happen.+data AttemptPurpose+ = PurposeDiscovery+ | PurposeHandshake+ | PurposeRequest+ | -- | The n-th retry of a request the server answered with a state-only+ -- interim result.+ PurposeContinuation !Int+ | PurposeListen+ | PurposeNotification+ | -- | A reply to a request a legacy server sent.+ PurposeReply+ | -- | Opening the deprecated HTTP+SSE event stream.+ PurposeEventStream+ | PurposeTeardown+ deriving stock (Eq, Show, Generic)++-- | What the hook is asked to approve. Contains no argument values.+data SendAttempt = SendAttempt+ { serverName :: !Text,+ endpoint :: !Text,+ -- | @scheme://host:port@ that will receive the request.+ origin :: !Text,+ method :: !Text,+ -- | The tool or prompt name, or the resource URI.+ target :: !(Maybe Text),+ -- | Present on a request for a page after the first.+ cursor :: !(Maybe Cursor),+ purpose :: !AttemptPurpose+ }+ deriving stock (Eq, Show, Generic)++-- | An extra header to send. Its value is never shown.+data SendHeader = SendHeader !HeaderName !ByteString++instance Show SendHeader where+ show (SendHeader n _) = "SendHeader " <> show n <> " <redacted>"++sendHeader :: HeaderName -> ByteString -> SendHeader+sendHeader = SendHeader++sendHeaderName :: SendHeader -> HeaderName+sendHeaderName (SendHeader n _) = n++data SendDecision+ = SendAllowed ![SendHeader]+ | SendDenied !Text+ deriving stock (Show)++-- | Runs before every transmission. Combine hooks with '<>': the left one+-- runs first, a denial stops the chain and allowed headers accumulate.+newtype McpRequestHook = McpRequestHook {runRequestHook :: SendAttempt -> IO SendDecision}++instance Semigroup McpRequestHook where+ McpRequestHook a <> McpRequestHook b = McpRequestHook $ \att -> do+ r <- a att+ case r of+ SendDenied why -> pure (SendDenied why)+ SendAllowed hs -> do+ r' <- b att+ pure $ case r' of+ SendDenied why -> SendDenied why+ SendAllowed hs' -> SendAllowed (hs <> hs')++instance Monoid McpRequestHook where+ mempty = McpRequestHook (const (pure (SendAllowed [])))++denyAll :: Text -> McpRequestHook+denyAll why = McpRequestHook (const (pure (SendDenied why)))++-- ---------------------------------------------------------------------------+-- Connections++-- | How headers and @_meta@ are written for the current stage.+data WireMode+ = ModeModern !ProtocolVersion+ | -- | Handshake era; 'Nothing' before @initialize@ completes.+ ModeLegacy !(Maybe ProtocolVersion)++data Wire = Wire+ { config :: !McpServerConfig,+ binding :: !Binding,+ mode :: !(IORef WireMode),+ session :: !(IORef (Maybe ByteString)),+ counter :: !(IORef Integer)+ }++data McpConnection = McpConnection+ { wire :: !Wire,+ description :: !ServerDescription,+ released :: !(IORef Bool),+ expired :: !(IORef Bool),+ listeners :: !(IORef (Map Int (IO ()))),+ listenerSeq :: !(IORef Int)+ }++connectionDescription :: McpConnection -> ServerDescription+connectionDescription c = c.description++connectionEra :: McpConnection -> Era+connectionEra c = c.description.era++connectionServerName :: McpConnection -> Text+connectionServerName c = c.wire.config.serverName++connectionBindingShape :: McpConnection -> BindingShape+connectionBindingShape c = c.wire.binding.shape++-- | How many subscription streams are open on this connection.+connectionOpenListeners :: McpConnection -> IO Int+connectionOpenListeners c = Map.size <$> readIORef c.listeners++-- | Open a connection using the process-wide TLS manager.+connectMcp :: McpServerConfig -> IO (Either McpError McpConnection)+connectMcp cfg = do+ mgr <- TLS.getGlobalManager+ connectMcpWith mgr cfg++-- | Open a connection with a caller-supplied HTTP manager.+connectMcpWith :: HTTP.Manager -> McpServerConfig -> IO (Either McpError McpConnection)+connectMcpWith mgr cfg = case parseEndpoint cfg.endpoint of+ Left why -> pure (Left (mcpError InvalidInput NotSent why))+ Right ep -> case cfg.profile of+ McpLegacyHttpSse -> connectHttpSse mgr cfg ep+ McpAuto -> connectWithBinding cfg (streamableHttpBinding mgr ep) PlanProbeThenLegacy+ McpModernOnly -> connectWithBinding cfg (streamableHttpBinding mgr ep) PlanModernOnly+ McpLegacyStreamableHttp -> connectWithBinding cfg (streamableHttpBinding mgr ep) (PlanHandshake legacyStreamableVersions)++connectHttpSse :: HTTP.Manager -> McpServerConfig -> HttpEndpoint -> IO (Either McpError McpConnection)+connectHttpSse mgr cfg ep = do+ let probeBinding = streamableHttpBinding mgr ep+ att =+ SendAttempt+ { serverName = cfg.serverName,+ endpoint = probeBinding.endpointText,+ origin = probeBinding.origin,+ method = "GET",+ target = Nothing,+ cursor = Nothing,+ purpose = PurposeEventStream+ }+ decision <- approve cfg att+ case decision of+ Left e -> pure (Left e)+ Right hdrs -> do+ opened <-+ openHttpSseBinding+ mgr+ ep+ (wireLimits cfg.limits)+ (micros cfg.limits.connectTimeout)+ hdrs+ case opened of+ Left e -> pure (Left e)+ Right b -> connectWithBinding cfg b (PlanHandshake (httpSseVersions <> legacyStreamableVersions))++-- | How a stream connection chooses its era.+data StreamProfile+ = -- | Probe with @server/discover@ and fall back to @initialize@ on any+ -- non-modern error or silence within 'probeTimeout'.+ StreamDetect+ | -- | Modern revisions only; never send @initialize@.+ StreamModernOnly+ | -- | A known handshake-era server; skip the probe.+ StreamLegacyOnly+ deriving stock (Eq, Show, Generic)++-- | Configuration for a connection over a caller-owned stream. A stdio+-- server takes its credentials from its environment, so the hook here+-- authorizes sends but its headers are ignored.+data McpStreamConfig = McpStreamConfig+ { -- | A non-secret identity for the server, shown to the request hook.+ streamName :: !Text,+ streamProfile :: !StreamProfile,+ -- | How long the probe waits before treating silence as legacy.+ probeTimeout :: !NominalDiffTime,+ streamLimits :: !McpLimits,+ streamRequestHook :: !McpRequestHook,+ streamClientInfo :: !(Maybe Implementation)+ }++mcpStreamConfig :: Text -> McpStreamConfig+mcpStreamConfig nm =+ McpStreamConfig+ { streamName = nm,+ streamProfile = StreamDetect,+ probeTimeout = 5,+ streamLimits = defaultMcpLimits,+ streamRequestHook = mempty,+ streamClientInfo = Just defaultClientInfo+ }++-- | Open a connection over a stream the caller owns. The caller keeps the+-- process; releasing the connection runs the stream's close action.+connectMcpStream :: McpStreamConfig -> McpStream -> IO (Either McpError McpConnection)+connectMcpStream sc s = do+ let label = "stream:" <> sc.streamName+ cfg =+ McpServerConfig+ { serverName = sc.streamName,+ endpoint = label,+ profile = McpAuto,+ limits = sc.streamLimits,+ requestHook = sc.streamRequestHook,+ clientInfo = sc.streamClientInfo+ }+ plan = case sc.streamProfile of+ StreamDetect -> PlanStreamProbe sc.probeTimeout legacyStreamableVersions+ StreamModernOnly -> PlanModernOnly+ StreamLegacyOnly -> PlanHandshake legacyStreamableVersions+ b <- streamBinding label (wireLimits sc.streamLimits) s+ connectWithBinding cfg b plan++-- | Open, run and always release.+withMcpStream :: McpStreamConfig -> McpStream -> (McpConnection -> IO a) -> IO (Either McpError a)+withMcpStream sc s k =+ bracket (connectMcpStream sc s) (either (const (pure ())) closeMcp) $ \case+ Left e -> pure (Left e)+ Right c -> Right <$> k c++-- | What opening a connection does on its binding.+data ConnectPlan+ = -- | @server/discover@, falling back to the handshake when allowed.+ PlanProbeThenLegacy+ | PlanModernOnly+ | -- | @initialize@ offering the first version, accepting any listed.+ PlanHandshake ![ProtocolVersion]+ | -- | Probe, and treat a non-modern error or silence within the given+ -- time as a legacy server (byte streams, which have no HTTP status).+ PlanStreamProbe !NominalDiffTime ![ProtocolVersion]++-- | Open a connection over an already-constructed binding. The binding is+-- released if opening fails.+connectWithBinding :: McpServerConfig -> Binding -> ConnectPlan -> IO (Either McpError McpConnection)+connectWithBinding cfg b plan = do+ m <- newIORef (ModeLegacy Nothing)+ s <- newIORef Nothing+ n <- newIORef 0+ let w = Wire {config = cfg, binding = b, mode = m, session = s, counter = n}+ forM_ b.unsolicited $ \ref -> writeIORef ref (answerServerRequest w)+ r <-+ ( timeout (micros cfg.limits.connectTimeout) (open w plan)+ >>= pure . fromMaybe (Left (mcpError TimedOut Uncertain "opening the MCP connection timed out"))+ )+ `onException` b.release+ case r of+ Left e -> b.release >> pure (Left e)+ Right desc -> do+ rel <- newIORef False+ ex <- newIORef False+ ls <- newIORef Map.empty+ sq <- newIORef 0+ pure (Right McpConnection {wire = w, description = desc, released = rel, expired = ex, listeners = ls, listenerSeq = sq})++open :: Wire -> ConnectPlan -> IO (Either McpError ServerDescription)+open w = \case+ PlanModernOnly -> do+ v <- probe w Nothing latestModernVersion+ case v of+ ProbeModern d -> pure (Right d)+ ProbeLegacy e -> pure (Left (setMessage ("the server does not speak a modern MCP revision (" <> e.message <> ")") e {kind = IncompatibleServer}))+ ProbeFailed e -> pure (Left e)+ PlanProbeThenLegacy -> do+ v <- probe w Nothing latestModernVersion+ case v of+ ProbeModern d -> pure (Right d)+ ProbeLegacy _ -> handshake w legacyStreamableVersions+ ProbeFailed e -> pure (Left e)+ PlanHandshake vs -> handshake w vs+ PlanStreamProbe wait vs -> do+ v <- probe w (Just wait) latestModernVersion+ case v of+ ProbeModern d -> pure (Right d)+ ProbeLegacy _ -> handshake w vs+ ProbeFailed e -> pure (Left e)++data ProbeVerdict+ = ProbeModern ServerDescription+ | -- | The answer identifies a handshake-era server.+ ProbeLegacy McpError+ | ProbeFailed McpError++-- | Send @server/discover@ at a version. On @UnsupportedProtocolVersion@+-- retry once with an implemented version the server lists.+probe :: Wire -> Maybe NominalDiffTime -> ProtocolVersion -> IO ProbeVerdict+probe w silenceIsLegacy v = do+ writeIORef w.mode (ModeModern v)+ r <- case silenceIsLegacy of+ Nothing -> sendOnce w PurposeDiscovery "server/discover" KeyMap.empty [] Nothing+ Just wait -> fromMaybe (Left silent) <$> timeout (micros wait) (sendOnce w PurposeDiscovery "server/discover" KeyMap.empty [] Nothing)+ case r of+ Right reply -> case reply.outcome of+ Right obj -> case decodeResultKind "server/discover" obj >> decodeDiscoverResult obj of+ Left why -> pure (ProbeFailed ((mcpError MalformedReply Answered ("unreadable server/discover result: " <> why)) {httpStatus = reply.status}))+ Right d -> case [x | x <- modernVersions, x `elem` d.supportedVersions] of+ (chosen : _) -> do+ writeIORef w.mode (ModeModern chosen)+ pure (ProbeModern d {era = Modern chosen})+ [] -> pure (ProbeFailed (incompatible reply.status d.supportedVersions))+ Left e+ | Just offered <- unsupportedVersionsOffered e ->+ case [x | x <- modernVersions, x `elem` offered, x /= v] of+ (other : _) -> probe w silenceIsLegacy other+ [] -> pure (ProbeFailed ((incompatible reply.status offered) {rpc = Just e}))+ | isModernErrorCode e.code -> pure (ProbeFailed (remote reply e))+ | maybe True legacyStatus reply.status -> pure (ProbeLegacy (remote reply e))+ | otherwise -> pure (ProbeFailed (remote reply e))+ Left e+ | e.kind == HttpFailure, e.delivery == Answered, maybe False legacyStatus e.httpStatus, e.httpStatus /= Just 401, e.httpStatus /= Just 403 -> pure (ProbeLegacy e)+ | e.kind == TimedOut, isJust silenceIsLegacy, e.message == silent.message -> pure (ProbeLegacy e)+ | otherwise -> pure (ProbeFailed e)+ where+ legacyStatus s = (s >= 200 && s < 300) || s `elem` [400, 404, 405]+ silent = mcpError TimedOut Uncertain "the server did not answer server/discover"+ incompatible st vs =+ (mcpError IncompatibleServer Answered ("the server supports none of the implemented protocol versions; it offers " <> Text.intercalate ", " (map (.versionText) vs)))+ { httpStatus = st+ }++-- | The handshake of 2025-11-25 and earlier.+handshake :: Wire -> [ProtocolVersion] -> IO (Either McpError ServerDescription)+handshake w allowed = do+ writeIORef w.mode (ModeLegacy Nothing)+ let preferred = case allowed of+ (v : _) -> v+ [] -> ProtocolVersion "2025-11-25"+ info = fromMaybe defaultClientInfo w.config.clientInfo+ params =+ KeyMap.fromList+ [ ("protocolVersion", toJSON preferred),+ ("capabilities", Object KeyMap.empty),+ ("clientInfo", toJSON info)+ ]+ r <- sendOnce w PurposeHandshake "initialize" params [] Nothing+ case r of+ Left e -> pure (Left e)+ Right reply -> case reply.outcome of+ Left e -> pure (Left (remote reply e))+ Right obj -> case decodeInitializeResult obj of+ Left why -> pure (Left ((mcpError MalformedReply Answered ("unreadable initialize result: " <> why)) {httpStatus = reply.status}))+ Right (v, desc)+ | v `notElem` allowed ->+ pure (Left ((mcpError IncompatibleServer Answered ("the server negotiated the unsupported protocol version " <> clipText 32 v.versionText)) {httpStatus = reply.status}))+ | otherwise -> do+ writeIORef w.session reply.sessionId+ writeIORef w.mode (ModeLegacy (Just v))+ sent <- notify w "notifications/initialized" KeyMap.empty+ pure (desc <$ sent)++-- ---------------------------------------------------------------------------+-- Sending++micros :: NominalDiffTime -> Int+micros t = max 1 (floor (realToFrac t * 1000000 :: Double))++wireLimits :: McpLimits -> WireLimits+wireLimits l = WireLimits {maxResponseBytes = l.maxResponseBytes, maxFrameBytes = l.maxFrameBytes}++-- | Ask the hook and check its headers.+approve :: McpServerConfig -> SendAttempt -> IO (Either McpError [Header])+approve cfg att = do+ d <- runRequestHook cfg.requestHook att+ pure $ case d of+ SendDenied why -> Left (mcpError RequestDenied NotSent ("the request hook refused " <> att.method <> ": " <> clipText 200 why))+ SendAllowed hs+ | any (isProtocolControlledHeader . sendHeaderName) hs ->+ Left (mcpError InvalidInput NotSent "the request hook supplied a header this client controls")+ | otherwise -> Right [(n, v) | SendHeader n v <- hs]++attemptFor :: Wire -> AttemptPurpose -> Text -> Object -> SendAttempt+attemptFor w p method params =+ SendAttempt+ { serverName = w.config.serverName,+ endpoint = w.binding.endpointText,+ origin = w.binding.origin,+ method = method,+ target = routingName method params,+ cursor = case KeyMap.lookup "cursor" params of+ Just (String c) -> Just (cursorFromText c)+ _ -> Nothing,+ purpose = p+ }++-- | Protocol headers for the current mode.+protocolHeaders :: Wire -> WireMode -> Text -> Object -> [ParamHeader] -> IO [Header]+protocolHeaders w m method params mirrors+ | w.binding.shape /= RequestScopedHttp = pure []+ | otherwise = case m of+ ModeModern v ->+ pure $+ [(hProtocolVersion, TE.encodeUtf8 v.versionText), (hMcpMethod, TE.encodeUtf8 method)]+ <> [(hMcpName, encodeHeaderValue n) | Just n <- [routingName method params]]+ <> [(paramHeaderField p, paramHeaderValue p) | p <- mirrors]+ ModeLegacy mv -> do+ s <- readIORef w.session+ pure $+ [(hProtocolVersion, TE.encodeUtf8 v.versionText) | Just v <- [mv], v.versionText >= "2025-06-18"]+ <> [(hSessionId, sid) | Just sid <- [s]]++-- | Send one request and return its correlated reply.+sendOnce :: Wire -> AttemptPurpose -> Text -> Object -> [ParamHeader] -> Maybe (Text -> Object -> IO ()) -> IO (Either McpError Reply)+sendOnce w p method params mirrors sink = do+ approved <- approve w.config (attemptFor w p method params)+ case approved of+ Left e -> pure (Left e)+ Right extra -> do+ m <- readIORef w.mode+ rid <- RequestIdNumber <$> atomicModifyIORef' w.counter (\c -> (c + 1, c + 1))+ phs <- protocolHeaders w m method params mirrors+ let params' = case m of+ ModeModern v -> withRequestMeta (requestMeta v w.config.clientInfo) params+ ModeLegacy _ -> params+ ex =+ Exchange+ { requestId = rid,+ method = method,+ body = BS.toStrict (Aeson.encode (encodeRequest rid method params')),+ headers = phs <> extra,+ onNotification = fromMaybe (\_ _ -> pure ()) sink,+ onServerRequest = answerServerRequest w+ }+ w.binding.exchange (wireLimits w.config.limits) ex++-- | Send a notification (legacy handshake only on HTTP).+notify :: Wire -> Text -> Object -> IO (Either McpError ())+notify w method params = do+ approved <- approve w.config (attemptFor w PurposeNotification method params)+ case approved of+ Left e -> pure (Left e)+ Right extra -> do+ m <- readIORef w.mode+ phs <- protocolHeaders w m method params []+ w.binding.post (phs <> extra) (BS.toStrict (Aeson.encode (encodeNotification method params)))++-- | Answer a request a legacy server sent: @ping@ gets an empty result;+-- anything else is a method this client does not implement.+answerServerRequest :: Wire -> RequestId -> Text -> Object -> IO ()+answerServerRequest w rid method _ = do+ approved <- approve w.config (attemptFor w PurposeReply method KeyMap.empty)+ case approved of+ Left _ -> pure ()+ Right extra -> do+ m <- readIORef w.mode+ phs <- protocolHeaders w m method KeyMap.empty []+ let reply+ | method == "ping" = encodeResultResponse rid KeyMap.empty+ | otherwise = encodeErrorResponse rid (rpcError methodNotFound "this client implements no server-initiated requests")+ r <- try @SomeException (w.binding.post (phs <> extra) (BS.toStrict (Aeson.encode reply)))+ either rethrowAsync (const (pure ())) r++remote :: Reply -> RpcError -> McpError+remote reply e =+ (mcpError RemoteRpcError Answered ("the server returned an error: " <> e.message))+ { httpStatus = reply.status,+ rpc = Just e+ }++-- ---------------------------------------------------------------------------+-- Requests++-- | A request for 'callMethod' or 'callInteractive'.+data McpCall = McpCall+ { method :: !Text,+ -- | Parameters without the protocol @_meta@ fields, which the client+ -- adds for the connection's era.+ params :: !Object,+ -- | Parameter mirrors for a modern @tools/call@ over HTTP.+ paramHeaders :: ![ParamHeader],+ -- | Receives request-scoped notifications (progress, logging).+ onNotification :: !(Maybe (Text -> Object -> IO ()))+ }++mcpCall :: Text -> Object -> McpCall+mcpCall m p = McpCall {method = m, params = p, paramHeaders = [], onNotification = Nothing}++-- | A completed result.+data CompleteResult = CompleteResult+ { -- | The whole result object, including fields this package does not+ -- model.+ result :: !Object,+ responseBytes :: !Int,+ -- | The server's freshness hint. Always 'Nothing' for a result reached+ -- through continuation rounds, which must not be cached.+ cache :: !(Maybe CacheHint),+ serverInfo :: !(Maybe Implementation),+ -- | Continuation rounds sent before the result completed.+ continuationRounds :: !Int+ }+ deriving stock (Eq, Show, Generic)++data UnfinishedReason+ = -- | The server asked for input (sampling, elicitation, roots) this+ -- client does not provide.+ NeedsClientInput+ | -- | The round limit was spent while the server kept answering with+ -- state alone.+ RoundLimitReached+ | -- | The request hook refused a continuation round.+ ContinuationDenied !Text+ deriving stock (Eq, Show, Generic)++-- | An interim result returned to the caller unanswered.+data Unfinished = Unfinished+ { inputRequests :: !(Maybe (Map Text Value)),+ requestState :: !(Maybe Text),+ roundsSent :: !Int,+ reason :: !UnfinishedReason+ }+ deriving stock (Eq, Show, Generic)++data McpOutcome a+ = McpCompleted !a+ | McpUnfinished !Unfinished+ deriving stock (Eq, Show, Generic, Functor)++-- | Fail early on a released or expired handle.+guarded :: McpConnection -> IO (Either McpError a) -> IO (Either McpError a)+guarded c act = do+ rel <- readIORef c.released+ ex <- readIORef c.expired+ if+ | rel -> pure (Left (mcpError ConnectionReleased NotSent "the MCP connection has been released"))+ | ex -> pure (Left (mcpError SessionExpired NotSent "the server's session has expired; open a new connection"))+ | otherwise -> act++withDeadline :: NominalDiffTime -> IO (Either McpError a) -> IO (Either McpError a)+withDeadline t act =+ fromMaybe (Left (mcpError TimedOut Uncertain "the MCP request timed out")) <$> timeout (micros t) act++-- | Turn a session-scoped 404 into an expiry and mark the handle.+noteExpiry :: McpConnection -> McpError -> IO McpError+noteExpiry c e = do+ s <- readIORef c.wire.session+ if isJust s && e.httpStatus == Just 404+ then do+ writeIORef c.expired True+ pure (setMessage "the server no longer recognizes this session; open a new connection" e {kind = SessionExpired})+ else pure e++-- | Send a request that may return an interim result. A state-only+-- interim result is continued — same method and parameters, the state+-- echoed exactly, a new request identifier — while rounds remain and the+-- hook allows each round. Interim results carrying input requests are+-- returned unanswered.+callInteractive :: McpConnection -> McpCall -> IO (Either McpError (McpOutcome CompleteResult))+callInteractive c call = guarded c . withDeadline c.wire.config.limits.requestTimeout $ go 0 Nothing+ where+ lim = c.wire.config.limits.maxContinuationRounds+ go :: Int -> Maybe Text -> IO (Either McpError (McpOutcome CompleteResult))+ go rounds st = do+ let purpose = if rounds == 0 then PurposeRequest else PurposeContinuation rounds+ params' = maybe call.params (\s -> KeyMap.insert "requestState" (String s) call.params) st+ r <- sendOnce c.wire purpose call.method params' call.paramHeaders call.onNotification+ case r of+ Left e+ | rounds > 0,+ e.kind == RequestDenied ->+ pure (Right (McpUnfinished Unfinished {inputRequests = Nothing, requestState = st, roundsSent = rounds - 1, reason = ContinuationDenied e.message}))+ | otherwise -> Left <$> noteExpiry c e+ Right reply -> case reply.outcome of+ Left e -> Left <$> noteExpiry c (remote reply e)+ Right obj -> case decodeResultKind call.method obj of+ Left why -> pure (Left ((mcpError MalformedReply Uncertain why) {httpStatus = reply.status}))+ Right ResultComplete -> case completeResult call.method rounds reply obj of+ Left why -> pure (Left ((mcpError MalformedReply Answered why) {httpStatus = reply.status}))+ Right cr -> pure (Right (McpCompleted cr))+ Right (ResultInputRequired ir) -> case (ir.inputRequests, ir.requestState) of+ (Just _, _) -> pure (Right (McpUnfinished (unfinished ir rounds NeedsClientInput)))+ (Nothing, Just s)+ | rounds >= lim -> pure (Right (McpUnfinished (unfinished ir rounds RoundLimitReached)))+ | otherwise -> go (rounds + 1) (Just s)+ (Nothing, Nothing) -> pure (Left (mcpError MalformedReply Answered "an interim result carried nothing to continue"))+ unfinished ir rounds why = Unfinished {inputRequests = ir.inputRequests, requestState = ir.requestState, roundsSent = rounds, reason = why}++completeResult :: Text -> Int -> Reply -> Object -> Either Text CompleteResult+completeResult method rounds reply obj = do+ hint <-+ if method `elem` cacheableMethods+ then decodeCacheHint obj+ else Right Nothing+ let info = case KeyMap.lookup "_meta" obj of+ Just (Object meta) | Just v <- KeyMap.lookup metaServerInfo meta -> either (const Nothing) Just (parseEither Aeson.parseJSON v)+ _ -> Nothing+ Right+ CompleteResult+ { result = obj,+ responseBytes = reply.bytes,+ cache = if rounds == 0 then hint else Nothing,+ serverInfo = info,+ continuationRounds = rounds+ }++-- | Send a request whose result is always complete. An interim result is+-- reported as an error.+callMethod :: McpConnection -> McpCall -> IO (Either McpError CompleteResult)+callMethod c call = do+ r <- callInteractive c call+ pure $ case r of+ Left e -> Left e+ Right (McpCompleted cr) -> Right cr+ Right (McpUnfinished u) ->+ Left (mcpError UnsupportedOperation Answered ("the server left " <> call.method <> " unfinished (" <> Text.pack (show u.reason) <> "); use callInteractive"))++-- | Request one page of a paginated list. @field@ names the array of+-- items; each item is decoded with the given parser.+requestPage :: McpConnection -> Text -> Aeson.Key -> (Value -> Parser a) -> Maybe Cursor -> IO (Either McpError (Page a))+requestPage c method field itemParser cur = do+ let params = maybe KeyMap.empty (\x -> KeyMap.singleton "cursor" (String (cursorToText x))) cur+ r <- callMethod c (mcpCall method params)+ pure $+ r >>= \cr -> case parseEither (pageParser cr) cr.result of+ Left why -> Left (mcpError MalformedReply Answered ("unreadable " <> method <> " page: " <> clipText 200 (Text.pack why)))+ Right p -> Right p+ where+ pageParser cr obj = do+ raw <- case KeyMap.lookup field obj of+ Just (Array xs) -> pure (foldr (:) [] xs)+ Just _ -> fail (show field <> " must be an array")+ Nothing -> fail ("missing " <> show field)+ xs <- traverse itemParser raw+ nc <- case KeyMap.lookup "nextCursor" obj of+ Nothing -> pure Nothing+ Just Null -> pure Nothing+ Just (String s) -> pure (Just (cursorFromText s))+ Just _ -> fail "nextCursor must be a string"+ pure Page {items = xs, nextCursor = nc, cache = cr.cache, responseBytes = cr.responseBytes}++-- ---------------------------------------------------------------------------+-- Lifecycle++-- | Release the connection: end open subscriptions, end a legacy session+-- (through the hook) and release the binding. Safe to call more than once.+closeMcp :: McpConnection -> IO ()+closeMcp c = mask $ \_ -> do+ was <- atomicModifyIORef' c.released (True,)+ unless was $ do+ ls <- atomicModifyIORef' c.listeners (Map.empty,)+ forM_ (Map.elems ls) $ \closeIt -> void (try @SomeException closeIt)+ s <- readIORef c.wire.session+ case (s, c.wire.binding.terminate) of+ (Just _, Just term) -> do+ approved <- approve c.wire.config (attemptFor c.wire PurposeTeardown "DELETE" KeyMap.empty)+ case approved of+ Left _ -> pure ()+ Right extra -> do+ m <- readIORef c.wire.mode+ phs <- protocolHeaders c.wire m "DELETE" KeyMap.empty []+ void (timeout (micros (min 5 c.wire.config.limits.requestTimeout)) (try @SomeException (term (phs <> extra))))+ _ -> pure ()+ c.wire.binding.release++-- | Open, run and always release.+withMcpConnection :: McpServerConfig -> (McpConnection -> IO a) -> IO (Either McpError a)+withMcpConnection cfg k =+ bracket (connectMcp cfg) (either (const (pure ())) closeMcp) $ \case+ Left e -> pure (Left e)+ Right c -> Right <$> k c++-- ---------------------------------------------------------------------------+-- Subscriptions++data SubscriptionEnd+ = -- | The server answered the listen request: a graceful end.+ EndedGracefully+ | -- | The server sent @notifications/cancelled@ for the subscription.+ EndedByServer+ | -- | The client released the subscription.+ EndedByClient+ | -- | The stream closed with neither signal.+ Disconnected+ | EndedWithError !McpError+ deriving stock (Eq, Show, Generic)++data SubscriptionEvent+ = SubscriptionNotification !Text !Object+ | SubscriptionEnded !SubscriptionEnd+ deriving stock (Eq, Show, Generic)++data Subscription = Subscription+ { sid :: !RequestId,+ requested :: !SubscriptionFilter,+ acknowledged :: !SubscriptionFilter,+ stream :: !MessageStream,+ ended :: !(IORef (Maybe SubscriptionEnd))+ }++subscriptionId :: Subscription -> RequestId+subscriptionId s = s.sid++subscriptionRequested :: Subscription -> SubscriptionFilter+subscriptionRequested s = s.requested++-- | What the server agreed to deliver: possibly a subset of the request.+subscriptionAcknowledged :: Subscription -> SubscriptionFilter+subscriptionAcknowledged s = s.acknowledged++-- | Open a @subscriptions/listen@ stream, wait for its acknowledgment and+-- run the action. The stream is closed when the action returns or throws,+-- and by 'closeMcp'. Modern connections only.+withSubscription :: McpConnection -> SubscriptionFilter -> (Subscription -> IO a) -> IO (Either McpError a)+withSubscription c flt k = guarded c $ case (c.description.era, c.wire.binding.openStream) of+ (Modern v, Just openIt) -> mask $ \restore -> do+ opened <- restore (withDeadline c.wire.config.limits.requestTimeout (openListen v openIt))+ case opened of+ Left e -> pure (Left e)+ Right sub -> do+ key <- atomicModifyIORef' c.listenerSeq (\n -> (n + 1, n + 1))+ let closeIt = do+ _ <- atomicModifyIORef' sub.ended (\e -> (Just (fromMaybe EndedByClient e), ()))+ sub.stream.close+ atomicModifyIORef' c.listeners (\m -> (Map.insert key closeIt m, ()))+ let cleanup = atomicModifyIORef' c.listeners (\m -> (Map.delete key m, ())) >> closeIt+ x <- restore (k sub) `onException` cleanup+ cleanup+ pure (Right x)+ _ -> pure (Left (mcpError UnsupportedOperation NotSent "subscriptions/listen requires a modern connection with a streaming binding"))+ where+ openListen v openIt = do+ let method = "subscriptions/listen"+ params = KeyMap.singleton "notifications" (toJSON flt)+ approved <- approve c.wire.config (attemptFor c.wire PurposeListen method params)+ case approved of+ Left e -> pure (Left e)+ Right extra -> do+ rid <- RequestIdNumber <$> atomicModifyIORef' c.wire.counter (\n -> (n + 1, n + 1))+ phs <- protocolHeaders c.wire (ModeModern v) method params []+ let ex =+ Exchange+ { requestId = rid,+ method = method,+ body = BS.toStrict (Aeson.encode (encodeRequest rid method (withRequestMeta (requestMeta v c.wire.config.clientInfo) params))),+ headers = phs <> extra,+ onNotification = \_ _ -> pure (),+ onServerRequest = \_ _ _ -> pure ()+ }+ s <- openIt (wireLimits c.wire.config.limits) ex+ case s of+ Left e -> pure (Left e)+ Right ms -> do+ ack <- awaitAck rid ms `onException` ms.close+ case ack of+ Left e -> ms.close >> pure (Left e)+ Right acked -> do+ e <- newIORef Nothing+ pure (Right Subscription {sid = rid, requested = flt, acknowledged = acked, stream = ms, ended = e})+ awaitAck rid ms = do+ item <- ms.next+ case item of+ StreamEnded Nothing -> pure (Left (mcpError TransportFailure Uncertain "the subscription stream ended before its acknowledgment"))+ StreamEnded (Just e) -> pure (Left e)+ StreamMessage (IncomingResponse _ (Left e)) -> pure (Left ((mcpError RemoteRpcError Answered ("the server refused the subscription: " <> e.message)) {rpc = Just e}))+ StreamMessage (IncomingResponse _ (Right _)) -> pure (Left (mcpError MalformedReply Answered "the subscription ended before its acknowledgment"))+ StreamMessage (IncomingRequest {}) -> awaitAck rid ms+ StreamMessage (IncomingNotification m p)+ | notificationSubscription p /= Just rid -> awaitAck rid ms+ | m /= "notifications/subscriptions/acknowledged" ->+ pure (Left (mcpError MalformedReply Answered "the server sent a notification before acknowledging the subscription"))+ | otherwise -> case KeyMap.lookup "notifications" p of+ Just v | Right f <- parseEither Aeson.parseJSON v -> pure (Right f)+ _ -> pure (Left (mcpError MalformedReply Answered "the subscription acknowledgment has no readable filter"))++notificationSubscription :: Object -> Maybe RequestId+notificationSubscription p = case KeyMap.lookup "_meta" p of+ Just (Object meta) | Just v <- KeyMap.lookup metaSubscriptionId meta -> either (const Nothing) Just (parseEither Aeson.parseJSON v)+ _ -> Nothing++-- | The next notification the acknowledged filter admits, or the end of+-- the subscription. Notifications for other subscriptions or of types not+-- acknowledged are skipped. Blocks until something arrives.+nextSubscriptionEvent :: Subscription -> IO SubscriptionEvent+nextSubscriptionEvent s = do+ done <- readIORef s.ended+ case done of+ Just e -> pure (SubscriptionEnded e)+ Nothing -> do+ item <- s.stream.next+ done' <- readIORef s.ended+ case (done', item) of+ (Just e, _) -> pure (SubscriptionEnded e)+ (_, StreamEnded Nothing) -> finish Disconnected+ (_, StreamEnded (Just e)) -> finish (EndedWithError e)+ (_, StreamMessage (IncomingResponse rid r))+ | rid == Just s.sid -> finish (either (\e -> EndedWithError ((mcpError RemoteRpcError Answered e.message) {rpc = Just e})) (const EndedGracefully) r)+ | otherwise -> nextSubscriptionEvent s+ (_, StreamMessage (IncomingRequest {})) -> nextSubscriptionEvent s+ (_, StreamMessage (IncomingNotification m p))+ | m == "notifications/cancelled",+ either (const Nothing) Just (maybe (Left "") (parseEither Aeson.parseJSON) (KeyMap.lookup "requestId" p)) == Just s.sid ->+ finish EndedByServer+ | notificationSubscription p /= Just s.sid -> nextSubscriptionEvent s+ | m `elem` subscriptionNotificationMethods s.acknowledged -> pure (SubscriptionNotification m p)+ | otherwise -> nextSubscriptionEvent s+ where+ finish e = do+ writeIORef s.ended (Just e)+ s.stream.close+ pure (SubscriptionEnded e)
+ src/Baikai/Mcp/Content.hs view
@@ -0,0 +1,37 @@+-- | Content blocks shared by tool results and prompt messages.+module Baikai.Mcp.Content+ ( ContentBlock (..),+ decodeContentBlock,+ )+where++import Data.Aeson (Value (..))+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Object)+import Data.Text (Text)+import GHC.Generics (Generic)++-- | One content block, decoded where this package models it and otherwise+-- preserved.+data ContentBlock+ = TextBlock !Text+ | -- | Base64 data, as sent, and its MIME type.+ ImageBlock !Text !Text+ | AudioBlock !Text !Text+ | -- | A link to a resource; never fetched here.+ ResourceLinkBlock !Object+ | EmbeddedResourceBlock !Object+ | -- | A block type this package does not model.+ OtherBlock !Value+ deriving stock (Eq, Show, Generic)++decodeContentBlock :: Value -> ContentBlock+decodeContentBlock v = case v of+ Object o -> case (KeyMap.lookup "type" o, KeyMap.lookup "text" o, KeyMap.lookup "data" o, KeyMap.lookup "mimeType" o) of+ (Just (String "text"), Just (String t), _, _) -> TextBlock t+ (Just (String "image"), _, Just (String d), Just (String m)) -> ImageBlock d m+ (Just (String "audio"), _, Just (String d), Just (String m)) -> AudioBlock d m+ (Just (String "resource_link"), _, _, _) -> ResourceLinkBlock o+ (Just (String "resource"), _, _, _) -> EmbeddedResourceBlock o+ _ -> OtherBlock v+ _ -> OtherBlock v
+ src/Baikai/Mcp/Error.hs view
@@ -0,0 +1,117 @@+-- | Failures of an MCP operation.+--+-- Every failure says whether the request reached the server. That matters+-- most for @tools/call@: a request that was 'NotSent' had no effect, one the+-- server 'Answered' with an error was refused, and one whose reply was lost+-- is 'Uncertain' — the remote action may have run. This package never+-- replays a request whose outcome is uncertain; the owner of the attempt+-- decides.+--+-- Values of 'McpError' are safe to render and log: they never carry+-- request or response headers, bodies, or credentials. Text that came from+-- the server is clipped.+module Baikai.Mcp.Error+ ( McpError (..),+ McpErrorKind (..),+ Delivery (..),+ mcpError,+ setMessage,+ renderMcpError,+ )+where++import Baikai.Error (BaikaiError)+import Baikai.Mcp.Protocol (RpcError (..), clipText)+import Control.Exception (Exception (..))+import Data.Text (Text)+import Data.Text qualified as Text+import GHC.Generics (Generic)++-- | Whether the server saw the request.+data Delivery+ = -- | Nothing was transmitted: a local check, the host's hook or a+ -- connection failure stopped the request first.+ NotSent+ | -- | The server answered definitively (an error response or status).+ Answered+ | -- | The request may have been processed but no usable reply arrived.+ Uncertain+ deriving stock (Eq, Ord, Show, Generic)++data McpErrorKind+ = -- | The host's request hook refused the send.+ RequestDenied+ | -- | The connection handle was already released.+ ConnectionReleased+ | -- | The server returned a JSON-RPC error; see 'rpc'.+ RemoteRpcError+ | -- | The server returned an HTTP failure status without a JSON-RPC+ -- error, or a status this client does not follow (such as a redirect).+ HttpFailure+ | -- | The network or the peer failed; see 'transport' for the core+ -- classification.+ TransportFailure+ | -- | The operation's deadline passed.+ TimedOut+ | -- | The reply could not be understood.+ MalformedReply+ | -- | A configured size, count or round limit was reached.+ LimitExceeded+ | -- | The server speaks no protocol version this client implements.+ IncompatibleServer+ | -- | A legacy server no longer recognizes the session it issued.+ SessionExpired+ | -- | The operation is not available on this connection's profile.+ UnsupportedOperation+ | -- | The request could not be built from the caller's input.+ InvalidInput+ deriving stock (Eq, Show, Generic)++data McpError = McpError+ { kind :: !McpErrorKind,+ -- | A bounded, credential-free description.+ message :: !Text,+ delivery :: !Delivery,+ -- | The HTTP status, when an HTTP response arrived.+ httpStatus :: !(Maybe Int),+ -- | The JSON-RPC error, when the server sent one.+ rpc :: !(Maybe RpcError),+ -- | The @WWW-Authenticate@ challenge of a 401 or 403 response.+ challenge :: !(Maybe Text),+ -- | Core's classification of a transport exception, including whether+ -- a fresh attempt could succeed.+ transport :: !(Maybe BaikaiError)+ }+ deriving stock (Eq, Show, Generic)++instance Exception McpError where+ displayException = Text.unpack . renderMcpError++mcpError :: McpErrorKind -> Delivery -> Text -> McpError+mcpError k d m =+ McpError+ { kind = k,+ message = clipText 512 m,+ delivery = d,+ httpStatus = Nothing,+ rpc = Nothing,+ challenge = Nothing,+ transport = Nothing+ }++-- | Replace the description, clipping it.+setMessage :: Text -> McpError -> McpError+setMessage m e = McpError {kind = e.kind, message = clipText 512 m, delivery = e.delivery, httpStatus = e.httpStatus, rpc = e.rpc, challenge = e.challenge, transport = e.transport}++-- | One line for a log or a user.+renderMcpError :: McpError -> Text+renderMcpError e =+ Text.intercalate+ " "+ ( [e.message]+ <> maybe [] (\s -> ["(HTTP " <> Text.pack (show s) <> ")"]) e.httpStatus+ <> maybe [] (\r -> ["(JSON-RPC " <> Text.pack (show r.code) <> ": " <> r.message <> ")"]) e.rpc+ <> case e.delivery of+ Uncertain -> ["[the server may have processed the request]"]+ _ -> []+ )
+ src/Baikai/Mcp/Internal/Binding.hs view
@@ -0,0 +1,103 @@+-- | The seam between the protocol client and a wire binding.+--+-- A binding moves already-encoded JSON-RPC messages. It knows nothing+-- about eras, @_meta@, hooks or continuation: the client layer in+-- "Baikai.Mcp.Client" decides what to send and with which headers, and a+-- binding delivers it and returns the correlated reply. Request-scoped+-- bindings (Streamable HTTP) read the reply from the response to the same+-- request; multiplexed bindings (the deprecated HTTP+SSE transport and+-- caller-owned byte streams) route replies from one shared channel with+-- "Baikai.Mcp.Internal.Mux".+--+-- This module is internal. Its contents may change in any release.+module Baikai.Mcp.Internal.Binding+ ( WireLimits (..),+ Exchange (..),+ Reply (..),+ StreamItem (..),+ MessageStream (..),+ Binding (..),+ BindingShape (..),+ )+where++import Baikai.Mcp.Error (McpError)+import Baikai.Mcp.Protocol (IncomingMessage, RequestId, RpcError)+import Data.Aeson.Types (Object)+import Data.ByteString (ByteString)+import Data.IORef (IORef)+import Data.Text (Text)+import Network.HTTP.Types (Header)++-- | Size ceilings a binding enforces while reading.+data WireLimits = WireLimits+ { -- | Bytes in one reply, including request-scoped notifications that+ -- precede it.+ maxResponseBytes :: !Int,+ -- | Bytes in one message, SSE event or line.+ maxFrameBytes :: !Int+ }++-- | One request to send and how to treat what arrives before its reply.+data Exchange = Exchange+ { requestId :: !RequestId,+ method :: !Text,+ body :: !ByteString,+ -- | Every header to send: protocol mirrors and the host hook's+ -- additions. Ignored by bindings without a header layer.+ headers :: ![Header],+ -- | A request-scoped notification (progress, log) arrived.+ onNotification :: Text -> Object -> IO (),+ -- | A legacy server sent a request on this reply's stream.+ onServerRequest :: RequestId -> Text -> Object -> IO ()+ }++-- | The correlated reply to an 'Exchange'.+data Reply = Reply+ { outcome :: !(Either RpcError Object),+ -- | Bytes read for this reply.+ bytes :: !Int,+ status :: !(Maybe Int),+ -- | A legacy @Mcp-Session-Id@ issued with the reply.+ sessionId :: !(Maybe ByteString)+ }++-- | What a long-lived stream yields.+data StreamItem+ = StreamMessage !IncomingMessage+ | -- | The stream ended: 'Nothing' for a clean end of input, or the+ -- failure that ended it.+ StreamEnded !(Maybe McpError)++data MessageStream = MessageStream+ { next :: IO StreamItem,+ -- | Release the stream. On HTTP this closes the response, which the+ -- server treats as cancellation; on a shared channel it sends+ -- @notifications/cancelled@. Safe to call more than once.+ close :: IO ()+ }++-- | Whether the binding has a per-request header layer.+data BindingShape = RequestScopedHttp | MultiplexedHttp | ByteStream+ deriving stock (Eq, Show)++data Binding = Binding+ { shape :: !BindingShape,+ -- | Rendered endpoint, without credentials, for diagnostics.+ endpointText :: !Text,+ -- | @scheme://host:port@ of the endpoint, for credential scoping.+ origin :: !Text,+ exchange :: WireLimits -> Exchange -> IO (Either McpError Reply),+ -- | Send a notification or a response; no reply is expected.+ post :: [Header] -> ByteString -> IO (Either McpError ()),+ -- | Open a long-lived reply stream (@subscriptions/listen@), when the+ -- binding supports one.+ openStream :: Maybe (WireLimits -> Exchange -> IO (Either McpError MessageStream)),+ -- | End a legacy session (HTTP @DELETE@), when the binding has one.+ terminate :: Maybe ([Header] -> IO ()),+ -- | Release every resource the binding owns. Idempotent.+ release :: IO (),+ -- | Where a multiplexed binding delivers server-initiated requests that+ -- belong to no exchange. Set by the client after construction.+ unsolicited :: !(Maybe (IORef (RequestId -> Text -> Object -> IO ())))+ }
+ src/Baikai/Mcp/Internal/Http.hs view
@@ -0,0 +1,224 @@+-- | HTTP plumbing shared by the Streamable HTTP and HTTP+SSE bindings.+--+-- This module is internal. Its contents may change in any release.+module Baikai.Mcp.Internal.Http+ ( -- * Endpoints+ HttpEndpoint (..),+ parseEndpoint,+ sameOrigin,++ -- * Responses+ withOpened,+ openResponse,+ openFailure,+ bodyFailure,+ readBounded,+ contentType,+ responseHeader,+ statusOf,+ rethrowAsync,++ -- * Server-sent events+ EventReader,+ newEventReader,+ nextEvent,+ eventReaderBytes,+ )+where++import Baikai.Mcp.Error+import Baikai.Mcp.Internal.Sse+import Baikai.Provider.Transport.Classify (classifyTransportException)+import Baikai.Url qualified as Url+import Control.Exception (SomeAsyncException, SomeException, fromException, mask, onException, throwIO, try)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Char8 qualified as BS8+import Data.IORef+import Data.Text (Text)+import Data.Text qualified as Text+import Network.HTTP.Client qualified as HTTP+import Network.HTTP.Types (HeaderName, hContentType, statusCode)++-- | A validated MCP endpoint.+data HttpEndpoint = HttpEndpoint+ { request :: !HTTP.Request,+ -- | Scheme, host and path, without credentials or query.+ rendered :: !Text,+ -- | @scheme://host:port@.+ origin :: !Text,+ scheme :: !Text,+ host :: !Text,+ port :: !Int+ }++-- | Accept an @http@ or @https@ URL without userinfo. The host is read by+-- "Baikai.Url", the one host parser every credential decision uses.+parseEndpoint :: Text -> Either Text HttpEndpoint+parseEndpoint raw = do+ parts <- maybe (Left "the MCP endpoint has no host") Right (Url.parseUrl raw)+ sch <- case Url.scheme parts of+ Just s | s == "http" || s == "https" -> Right s+ Just s -> Left ("the MCP endpoint uses the unsupported scheme " <> s)+ Nothing -> Left "the MCP endpoint has no scheme; start it with https:// or http://"+ if Url.hasUserInfo parts+ then Left "the MCP endpoint must not embed credentials; supply them through the request hook"+ else Right ()+ req <- either (const (Left "the MCP endpoint is not a valid URL")) Right (HTTP.parseRequest @(Either SomeException) (Text.unpack (Text.strip raw)))+ let p = case Url.port parts of+ Just n -> n+ Nothing -> if sch == "https" then 443 else 80+ h = Url.host parts+ Right+ HttpEndpoint+ { request = req,+ rendered = Url.renderEndpoint parts,+ origin = sch <> "://" <> h <> ":" <> Text.pack (show p),+ scheme = sch,+ host = h,+ port = p+ }++sameOrigin :: HttpEndpoint -> HttpEndpoint -> Bool+sameOrigin a b = a.origin == b.origin++-- | Re-throw asynchronous exceptions (cancellation, timeouts) untouched.+rethrowAsync :: SomeException -> IO ()+rethrowAsync e = case fromException @SomeAsyncException e of+ Just _ -> throwIO e+ Nothing -> pure ()++-- | Open a response and always close it. A failure to open is classified+-- by phase; a synchronous failure while the continuation reads the body+-- is a lost reply.+withOpened :: HTTP.Manager -> HTTP.Request -> (HTTP.Response HTTP.BodyReader -> IO (Either McpError a)) -> IO (Either McpError a)+withOpened mgr req k = mask $ \restore -> do+ r <- try (restore (HTTP.responseOpen req mgr))+ case r of+ Left e -> rethrowAsync e >> pure (Left (openFailure e))+ Right resp -> do+ x <- try (restore (k resp)) `onException` HTTP.responseClose resp+ HTTP.responseClose resp+ case x of+ Left e -> rethrowAsync e >> pure (Left (bodyFailure e))+ Right v -> pure v++-- | Open a response whose lifetime the caller manages.+openResponse :: HTTP.Manager -> HTTP.Request -> IO (Either McpError (HTTP.Response HTTP.BodyReader))+openResponse mgr req = do+ r <- try (HTTP.responseOpen req mgr)+ case r of+ Left e -> rethrowAsync e >> pure (Left (openFailure e))+ Right resp -> pure (Right resp)++-- | A failure before a response arrived. Only failures that certainly+-- precede transmission are 'NotSent'.+openFailure :: SomeException -> McpError+openFailure e =+ (mcpError TransportFailure delivery ("could not complete the HTTP exchange: " <> describe e))+ { transport = classifyTransportException e+ }+ where+ delivery = case fromException e of+ Just (HTTP.InvalidUrlException _ _) -> NotSent+ Just (HTTP.HttpExceptionRequest _ c) -> case c of+ HTTP.ConnectionFailure _ -> NotSent+ HTTP.ConnectionTimeout -> NotSent+ HTTP.InvalidDestinationHost _ -> NotSent+ HTTP.InvalidRequestHeader _ -> NotSent+ HTTP.ProxyConnectException {} -> NotSent+ HTTP.TlsNotSupported -> NotSent+ _ -> Uncertain+ Nothing -> Uncertain++-- | A failure while reading a response body.+bodyFailure :: SomeException -> McpError+bodyFailure e =+ (mcpError TransportFailure Uncertain ("the response was interrupted: " <> describe e))+ { transport = classifyTransportException e+ }++describe :: SomeException -> Text+describe e = case fromException e of+ Just (HTTP.HttpExceptionRequest _ c) -> Text.pack (takeWhile (/= ' ') (show c))+ Just (HTTP.InvalidUrlException _ _) -> "invalid URL"+ Nothing -> Text.take 120 (Text.pack (takeWhile (/= '\n') (show e)))++-- | Read a whole body, refusing more than the limit. 'Left' carries the+-- number of bytes read when the limit was reached.+readBounded :: Int -> HTTP.BodyReader -> IO (Either Int ByteString)+readBounded limit br = go 0 []+ where+ go n acc = do+ chunk <- HTTP.brRead br+ if BS.null chunk+ then pure (Right (BS.concat (reverse acc)))+ else+ let n' = n + BS.length chunk+ in if n' > limit then pure (Left n') else go n' (chunk : acc)++-- | The media type of a response, lower-cased, without parameters.+contentType :: HTTP.Response a -> Maybe ByteString+contentType resp =+ BS8.map toLowerAscii . BS8.strip . BS8.takeWhile (/= ';') <$> lookup hContentType (HTTP.responseHeaders resp)+ where+ toLowerAscii c = if c >= 'A' && c <= 'Z' then toEnum (fromEnum c + 32) else c++responseHeader :: HeaderName -> HTTP.Response a -> Maybe ByteString+responseHeader n resp = lookup n (HTTP.responseHeaders resp)++statusOf :: HTTP.Response a -> Int+statusOf = statusCode . HTTP.responseStatus++-- | Reads events from a response body under a frame limit and, optionally,+-- a total byte limit.+data EventReader = EventReader+ { body :: !HTTP.BodyReader,+ parser :: !(IORef SseParser),+ pending :: !(IORef [SseEvent]),+ total :: !(IORef Int),+ maxTotal :: !(Maybe Int),+ finished :: !(IORef Bool)+ }++newEventReader :: Int -> Maybe Int -> HTTP.BodyReader -> IO EventReader+newEventReader frame maxT br = do+ p <- newIORef (newSseParser frame)+ q <- newIORef []+ t <- newIORef 0+ f <- newIORef False+ pure EventReader {body = br, parser = p, pending = q, total = t, maxTotal = maxT, finished = f}++eventReaderBytes :: EventReader -> IO Int+eventReaderBytes r = readIORef r.total++-- | The next event; @Right Nothing@ at end of stream.+nextEvent :: EventReader -> IO (Either McpError (Maybe SseEvent))+nextEvent r = do+ queued <- readIORef r.pending+ case queued of+ (e : es) -> writeIORef r.pending es >> pure (Right (Just e))+ [] -> do+ done <- readIORef r.finished+ if done+ then pure (Right Nothing)+ else do+ chunk <- HTTP.brRead r.body+ if BS.null chunk+ then writeIORef r.finished True >> pure (Right Nothing)+ else do+ n <- atomicModifyIORef' r.total (\t -> let t' = t + BS.length chunk in (t', t'))+ case r.maxTotal of+ Just m | n > m -> do+ writeIORef r.finished True+ pure (Left (mcpError LimitExceeded Uncertain "the response exceeded the configured size limit"))+ _ -> do+ st <- readIORef r.parser+ case feedSse st chunk of+ Left why -> do+ writeIORef r.finished True+ pure (Left (mcpError LimitExceeded Uncertain (Text.pack why)))+ Right (st', evs) -> do+ writeIORef r.parser st'+ writeIORef r.pending evs+ nextEvent r
+ src/Baikai/Mcp/Internal/Mux.hs view
@@ -0,0 +1,137 @@+-- | Reply routing for bindings where every message shares one channel: the+-- deprecated HTTP+SSE transport and caller-owned byte streams.+--+-- One reader feeds 'dispatch'. A request registers a waiter /before/ it+-- is written, so its reply cannot race past it. A response whose waiter is+-- gone (cancelled or timed out) is dropped. Notifications carrying an+-- @io.modelcontextprotocol/subscriptionId@ go to the listener registered+-- under that identifier; a server's @notifications/cancelled@ for a+-- listener and the response to a listener's own request both end it. When+-- the channel fails every waiter and listener receives that failure.+--+-- This module is internal. Its contents may change in any release.+module Baikai.Mcp.Internal.Mux+ ( Mux,+ newMux,+ register,+ unregister,+ await,+ registerListener,+ unregisterListener,+ dispatch,+ failAll,+ failure,+ )+where++import Baikai.Mcp.Error+import Baikai.Mcp.Internal.Binding+import Baikai.Mcp.Protocol+import Control.Concurrent.STM+import Data.Aeson (Value (..), fromJSON)+import Data.Aeson qualified as Aeson+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Object)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Text (Text)++data Mux = Mux+ { waiters :: !(TVar (Map RequestId (TMVar (Either McpError Reply)))),+ listeners :: !(TVar (Map RequestId (TQueue StreamItem))),+ failed :: !(TVar (Maybe McpError)),+ unsolicitedRequest :: RequestId -> Text -> Object -> IO ()+ }++newMux :: (RequestId -> Text -> Object -> IO ()) -> IO Mux+newMux onRequest = do+ w <- newTVarIO Map.empty+ l <- newTVarIO Map.empty+ f <- newTVarIO Nothing+ pure Mux {waiters = w, listeners = l, failed = f, unsolicitedRequest = onRequest}++failure :: Mux -> IO (Maybe McpError)+failure m = readTVarIO m.failed++-- | Register a waiter for a request about to be written.+register :: Mux -> RequestId -> IO (Either McpError (TMVar (Either McpError Reply)))+register m rid = atomically $ do+ f <- readTVar m.failed+ case f of+ Just e -> pure (Left e {delivery = NotSent})+ Nothing -> do+ v <- newEmptyTMVar+ modifyTVar' m.waiters (Map.insert rid v)+ pure (Right v)++unregister :: Mux -> RequestId -> IO ()+unregister m rid = atomically (modifyTVar' m.waiters (Map.delete rid))++await :: TMVar (Either McpError Reply) -> IO (Either McpError Reply)+await = atomically . readTMVar++registerListener :: Mux -> RequestId -> IO (Either McpError (TQueue StreamItem))+registerListener m rid = atomically $ do+ f <- readTVar m.failed+ case f of+ Just e -> pure (Left e {delivery = NotSent})+ Nothing -> do+ q <- newTQueue+ modifyTVar' m.listeners (Map.insert rid q)+ pure (Right q)++unregisterListener :: Mux -> RequestId -> IO ()+unregisterListener m rid = atomically (modifyTVar' m.listeners (Map.delete rid))++-- | Route one message read from the channel. @size@ is its byte count.+dispatch :: Mux -> Int -> IncomingMessage -> IO ()+dispatch m size = \case+ -- A response nobody waits for belongs to a cancelled request and is+ -- dropped.+ IncomingResponse (Just rid) r -> atomically $ do+ ws <- readTVar m.waiters+ case Map.lookup rid ws of+ Just v -> do+ _ <- tryPutTMVar v (Right Reply {outcome = r, bytes = size, status = Nothing, sessionId = Nothing})+ modifyTVar' m.waiters (Map.delete rid)+ Nothing -> do+ ls <- readTVar m.listeners+ case Map.lookup rid ls of+ Just q -> writeTQueue q (StreamMessage (IncomingResponse (Just rid) r))+ Nothing -> pure ()+ IncomingResponse Nothing _ -> pure ()+ msg@(IncomingNotification method params) -> atomically $ do+ ls <- readTVar m.listeners+ let target = case subscriptionOf params of+ Just sid -> Just sid+ Nothing+ | method == "notifications/cancelled" -> cancelledId params+ | otherwise -> Nothing+ case target >>= (`Map.lookup` ls) of+ Just q -> writeTQueue q (StreamMessage msg)+ Nothing -> pure ()+ IncomingRequest rid method params -> m.unsolicitedRequest rid method params++subscriptionOf :: Object -> Maybe RequestId+subscriptionOf params = case KeyMap.lookup "_meta" params of+ Just (Object meta) -> KeyMap.lookup metaSubscriptionId meta >>= fromResult . fromJSON+ _ -> Nothing++cancelledId :: Object -> Maybe RequestId+cancelledId params = KeyMap.lookup "requestId" params >>= fromResult . fromJSON++fromResult :: Aeson.Result a -> Maybe a+fromResult = \case+ Aeson.Success a -> Just a+ Aeson.Error _ -> Nothing++-- | The channel ended: fail every waiter and listener and refuse new ones.+failAll :: Mux -> McpError -> IO ()+failAll m e = atomically $ do+ writeTVar m.failed . Just =<< (maybe e id <$> readTVar m.failed)+ ws <- readTVar m.waiters+ mapM_ (\v -> tryPutTMVar v (Left e)) (Map.elems ws)+ writeTVar m.waiters Map.empty+ ls <- readTVar m.listeners+ mapM_ (\q -> writeTQueue q (StreamEnded (Just e))) (Map.elems ls)+ writeTVar m.listeners Map.empty
+ src/Baikai/Mcp/Internal/Sse.hs view
@@ -0,0 +1,104 @@+-- | An incremental, bounded Server-Sent Events parser.+--+-- Chunks arrive from the network at arbitrary boundaries, so a line, a+-- field or a CRLF pair can straddle two chunks. The parser keeps the+-- partial line and refuses any line or event larger than its limit before+-- it buffers more, so a hostile stream cannot grow memory without bound.+-- Comment lines (those starting with @:@) are keep-alives and are ignored.+-- An incomplete event at end of stream is discarded, as the SSE+-- specification requires.+module Baikai.Mcp.Internal.Sse+ ( SseEvent (..),+ SseParser,+ newSseParser,+ feedSse,+ )+where++import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Char8 qualified as BS8+import GHC.Generics (Generic)++-- | One dispatched event.+data SseEvent = SseEvent+ { -- | The @event:@ field, empty when absent (which means @message@).+ eventName :: !ByteString,+ -- | The @data:@ lines joined with newlines.+ eventData :: !ByteString+ }+ deriving stock (Eq, Show, Generic)++data SseParser = SseParser+ { limit :: !Int,+ partial :: !ByteString,+ -- | The previous chunk ended with CR, so a leading LF belongs to it.+ skipLF :: !Bool,+ dataLines :: ![ByteString],+ dataSize :: !Int,+ name :: !ByteString+ }++-- | A parser refusing any line or event larger than the given byte count.+newSseParser :: Int -> SseParser+newSseParser n = SseParser {limit = n, partial = BS.empty, skipLF = False, dataLines = [], dataSize = 0, name = BS.empty}++-- | Feed one chunk. Returns the events completed by it, or a reason when+-- the size limit is exceeded.+feedSse :: SseParser -> ByteString -> Either String (SseParser, [SseEvent])+feedSse st0 chunk0+ | BS.null chunk0 = Right (st0, [])+ | otherwise = go st0 {skipLF = False} chunk' []+ where+ chunk'+ | st0.skipLF, Just ('\n', rest) <- BS8.uncons chunk0 = rest+ | otherwise = chunk0+ go st input acc+ | BS.null input = Right (st, reverse acc)+ | otherwise = case BS8.findIndex (\c -> c == '\n' || c == '\r') input of+ Nothing ->+ let buf = st.partial <> input+ in if BS.length buf > st.limit+ then Left "server-sent event line exceeds the frame limit"+ else Right (st {partial = buf, skipLF = False}, reverse acc)+ Just i -> do+ let line = st.partial <> BS.take i input+ terminator = BS8.index input i+ after = BS.drop (i + 1) input+ (rest, pendingLF) =+ if terminator == '\r'+ then case BS8.uncons after of+ Just ('\n', r) -> (r, False)+ Just _ -> (after, False)+ Nothing -> (after, True)+ else (after, False)+ if BS.length line > st.limit+ then Left "server-sent event line exceeds the frame limit"+ else do+ (st', ev) <- processLine st {partial = BS.empty} line+ go st' {skipLF = pendingLF} rest (maybe acc (: acc) ev)++processLine :: SseParser -> ByteString -> Either String (SseParser, Maybe SseEvent)+processLine st line+ | BS.null line =+ if null st.dataLines+ then Right (reset, Nothing)+ else Right (reset, Just (SseEvent st.name (BS.intercalate "\n" (reverse st.dataLines))))+ | BS8.head line == ':' = Right (st, Nothing)+ | otherwise =+ let (field, rest0) = BS8.break (== ':') line+ value = case BS8.uncons rest0 of+ Just (':', v) -> case BS8.uncons v of+ Just (' ', v') -> v'+ _ -> v+ _ -> BS.empty+ in case field of+ "data" ->+ let size = st.dataSize + BS.length value + 1+ in if size > st.limit+ then Left "server-sent event exceeds the frame limit"+ else Right (st {dataLines = value : st.dataLines, dataSize = size}, Nothing)+ "event" -> Right (st {name = value}, Nothing)+ _ -> Right (st, Nothing)+ where+ reset = st {dataLines = [], dataSize = 0, name = BS.empty}
+ src/Baikai/Mcp/JsonSchema.hs view
@@ -0,0 +1,491 @@+-- | Bounded JSON Schema 2020-12 validation for MCP tool output.+--+-- MCP schemas default to JSON Schema 2020-12 and may use composition and+-- local references. A schema comes from a remote server, so evaluation is+-- bounded: every keyword and every subschema application spends one unit+-- of a fuel budget, nesting is capped, and a budget that runs out yields+-- 'Unverifiable' rather than an answer. Nothing is ever fetched: a+-- reference that does not point into the same document is 'Unverifiable'.+--+-- The validation and applicator vocabularies are implemented. Keywords+-- whose semantics this module does not implement — @$dynamicRef@,+-- @unevaluatedProperties@, @unevaluatedItems@, references to anchors,+-- nested @$id@, a dialect other than 2020-12, and @pattern@ syntax outside+-- the portable subset (no look-around, back-references or Unicode+-- property classes) — make the verdict 'Unverifiable' instead of being+-- ignored, so an unsupported contract is never reported as satisfied.+-- @format@ and the @content*@ keywords are annotations, as 2020-12+-- specifies by default.+module Baikai.Mcp.JsonSchema+ ( SchemaBudget (..),+ defaultSchemaBudget,+ SchemaVerdict (..),+ SchemaViolation (..),+ validateJson,+ )+where++import Data.Aeson (Value (..))+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Char (chr, isDigit, isHexDigit)+import Data.Foldable (toList)+import Data.List (nub)+import Data.Ratio (denominator)+import Data.Scientific (Scientific, base10Exponent, floatingOrInteger, isInteger)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Vector qualified as Vector+import GHC.Generics (Generic)+import Numeric (readHex)+import Text.Regex.TDFA (CompOption (..), Regex, defaultCompOpt, defaultExecOpt, makeRegexOptsM, matchTest)++data SchemaBudget = SchemaBudget+ { -- | Keyword evaluations and subschema applications allowed.+ maxSteps :: !Int,+ -- | Nested subschema applications allowed.+ maxDepth :: !Int,+ -- | Violations reported at most.+ maxViolations :: !Int+ }+ deriving stock (Eq, Show, Generic)++defaultSchemaBudget :: SchemaBudget+defaultSchemaBudget = SchemaBudget {maxSteps = 200000, maxDepth = 64, maxViolations = 16}++data SchemaViolation = SchemaViolation+ { -- | JSON Pointer to the offending part of the instance.+ instancePath :: !Text,+ keyword :: !Text,+ detail :: !Text+ }+ deriving stock (Eq, Show, Generic)++data SchemaVerdict+ = Conforms+ | Violates ![SchemaViolation]+ | -- | The schema could not be evaluated within budget or uses something+ -- this validator does not implement.+ Unverifiable !Text+ deriving stock (Eq, Show, Generic)++-- ---------------------------------------------------------------------------+-- Evaluation monad: fuel and early stop++data Stop = StopUnsupported Text | StopBudget Text++newtype Eval a = Eval {runEval :: Int -> Either Stop (a, Int)}++instance Functor Eval where+ fmap f (Eval g) = Eval $ \n -> case g n of+ Left s -> Left s+ Right (a, n') -> Right (f a, n')++instance Applicative Eval where+ pure a = Eval $ \n -> Right (a, n)+ Eval f <*> Eval g = Eval $ \n -> case f n of+ Left s -> Left s+ Right (h, n') -> case g n' of+ Left s -> Left s+ Right (a, n'') -> Right (h a, n'')++instance Monad Eval where+ Eval g >>= k = Eval $ \n -> case g n of+ Left s -> Left s+ Right (a, n') -> runEval (k a) n'++tick :: Eval ()+tick = Eval $ \n -> if n <= 0 then Left (StopBudget "the schema evaluation budget was exhausted") else Right ((), n - 1)++unsupported :: Text -> Eval a+unsupported why = Eval (const (Left (StopUnsupported why)))++data Ctx = Ctx {root :: !Value, depth :: !Int, budget :: !SchemaBudget}++-- | Validate an instance against a schema document.+validateJson :: SchemaBudget -> Value -> Value -> SchemaVerdict+validateJson b schema inst =+ case checkRoot schema of+ Just why -> Unverifiable why+ Nothing -> case runEval (validate (Ctx schema 0 b) [] schema inst) b.maxSteps of+ Left (StopUnsupported why) -> Unverifiable why+ Left (StopBudget why) -> Unverifiable why+ Right ([], _) -> Conforms+ Right (vs, _) -> Violates (take b.maxViolations vs)++checkRoot :: Value -> Maybe Text+checkRoot = \case+ Object o -> case KeyMap.lookup "$schema" o of+ Nothing -> Nothing+ Just (String s)+ | s `elem` ["https://json-schema.org/draft/2020-12/schema", "https://json-schema.org/draft/2020-12/schema#"] -> Nothing+ | otherwise -> Just ("the schema dialect " <> Text.take 80 s <> " is not supported")+ Just _ -> Just "$schema must be a string"+ Bool _ -> Nothing+ _ -> Just "a schema must be an object or a boolean"++type Path = [Text]++pointer :: Path -> Text+pointer [] = ""+pointer ps = Text.concat (map (\p -> "/" <> Text.replace "/" "~1" (Text.replace "~" "~0" p)) (reverse ps))++violation :: Path -> Text -> Text -> [SchemaViolation]+violation p k d = [SchemaViolation {instancePath = pointer p, keyword = k, detail = d}]++unsupportedKeywords :: [Text]+unsupportedKeywords = ["$dynamicRef", "$dynamicAnchor", "$recursiveRef", "$recursiveAnchor", "unevaluatedProperties", "unevaluatedItems"]++validate :: Ctx -> Path -> Value -> Value -> Eval [SchemaViolation]+validate ctx path schema inst = do+ tick+ if ctx.depth > ctx.budget.maxDepth+ then Eval (const (Left (StopBudget "the schema nests too deeply")))+ else case schema of+ Bool True -> pure []+ Bool False -> pure (violation path "false" "no value is allowed here")+ Object o -> do+ mapM_ (\k -> if Key.toText k `elem` unsupportedKeywords then unsupported ("the keyword " <> Key.toText k <> " is not supported") else pure ()) (KeyMap.keys o)+ case KeyMap.lookup "$id" o of+ Just _ | ctx.depth > 0 -> unsupported "nested $id is not supported"+ _ -> pure ()+ case KeyMap.lookup "$schema" o of+ Just _ | ctx.depth > 0 -> unsupported "a nested $schema is not supported"+ _ -> pure ()+ let ctx' = ctx {depth = ctx.depth + 1}+ concat+ <$> sequence+ [ refKeyword ctx' path o inst,+ typeKeyword path o inst,+ enumKeywords path o inst,+ numberKeywords path o inst,+ stringKeywords path o inst,+ arrayKeywords ctx' path o inst,+ objectKeywords ctx' path o inst,+ combinators ctx' path o inst+ ]+ _ -> unsupported "a subschema must be an object or a boolean"++-- | Apply a subschema; True when it holds.+holds :: Ctx -> Path -> Value -> Value -> Eval Bool+holds ctx p s v = null <$> validate ctx p s v++refKeyword :: Ctx -> Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]+refKeyword ctx path o inst = case KeyMap.lookup "$ref" o of+ Nothing -> pure []+ Just (String ref) -> case resolvePointer ctx.root ref of+ Left why -> unsupported why+ Right target -> validate ctx path target inst+ Just _ -> unsupported "$ref must be a string"++-- | Resolve a same-document reference (@#@ followed by a JSON Pointer).+resolvePointer :: Value -> Text -> Either Text Value+resolvePointer root ref+ | not ("#" `Text.isPrefixOf` ref) = Left ("the reference " <> Text.take 80 ref <> " is not local and is never fetched")+ | otherwise =+ let frag = percentDecode (Text.drop 1 ref)+ in if Text.null frag+ then Right root+ else+ if not ("/" `Text.isPrefixOf` frag)+ then Left "references to anchors are not supported"+ else walk root (map unescape (drop 1 (Text.splitOn "/" frag)))+ where+ unescape = Text.replace "~0" "~" . Text.replace "~1" "/"+ walk v [] = Right v+ walk (Object m) (k : ks) = maybe (Left ("unresolvable reference " <> Text.take 80 ref)) (`walk` ks) (KeyMap.lookup (Key.fromText k) m)+ walk (Array xs) (k : ks)+ | Text.all isDigit k, not (Text.null k), Just x <- xs Vector.!? read (Text.unpack k) = walk x ks+ walk _ _ = Left ("unresolvable reference " <> Text.take 80 ref)++percentDecode :: Text -> Text+percentDecode t = case Text.breakOn "%" t of+ (a, rest)+ | Text.null rest -> a+ | otherwise ->+ let hex = Text.take 2 (Text.drop 1 rest)+ in case readHex (Text.unpack hex) of+ [(n, "")] | Text.length hex == 2, Text.all isHexDigit hex -> a <> Text.singleton (chr n) <> percentDecode (Text.drop 3 rest)+ _ -> a <> "%" <> percentDecode (Text.drop 1 rest)++typeName :: Value -> [Text]+typeName = \case+ Null -> ["null"]+ Bool _ -> ["boolean"]+ String _ -> ["string"]+ Array _ -> ["array"]+ Object _ -> ["object"]+ Number n -> if isInteger n || isWhole n then ["number", "integer"] else ["number"]+ where+ isWhole n = case floatingOrInteger @Double n of+ Right (_ :: Integer) -> True+ Left _ -> False++typeKeyword :: Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]+typeKeyword path o inst = case KeyMap.lookup "type" o of+ Nothing -> pure []+ Just t -> do+ tick+ allowed <- case t of+ String s -> pure [s]+ Array xs -> traverse (\case String s -> pure s; _ -> unsupported "type entries must be strings") (toList xs)+ _ -> unsupported "type must be a string or an array"+ pure $+ if any (`elem` typeName inst) allowed+ then []+ else violation path "type" ("expected " <> Text.intercalate " or " allowed)++enumKeywords :: Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]+enumKeywords path o inst = do+ e <- case KeyMap.lookup "enum" o of+ Nothing -> pure []+ Just (Array xs) -> tick >> pure (if inst `elem` toList xs then [] else violation path "enum" "not one of the allowed values")+ Just _ -> unsupported "enum must be an array"+ c <- case KeyMap.lookup "const" o of+ Nothing -> pure []+ Just v -> tick >> pure (if v == inst then [] else violation path "const" "not the required value")+ pure (e <> c)++numberKeywords :: Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]+numberKeywords path o = \case+ Number n -> concat <$> traverse (check n) ["multipleOf", "maximum", "exclusiveMaximum", "minimum", "exclusiveMinimum"]+ _ -> pure []+ where+ check n k = case KeyMap.lookup (Key.fromText k) o of+ Nothing -> pure []+ Just (Number b) -> do+ tick+ ok <- case k of+ "multipleOf"+ | b <= 0 -> unsupported "multipleOf must be positive"+ | tooLarge n || tooLarge b -> unsupported "a number is too large to check multipleOf"+ | otherwise -> pure (denominator (toRational n / toRational b) == 1)+ "maximum" -> pure (n <= b)+ "exclusiveMaximum" -> pure (n < b)+ "minimum" -> pure (n >= b)+ _ -> pure (n > b)+ pure (if ok then [] else violation path k ("violates " <> k))+ Just _ -> unsupported (k <> " must be a number")+ tooLarge :: Scientific -> Bool+ tooLarge s = abs (base10Exponent s) > 400++stringKeywords :: Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]+stringKeywords path o = \case+ String s -> do+ lenV <- concat <$> traverse (lengthCheck s) [("maxLength", (<=)), ("minLength", (>=))]+ patV <- case KeyMap.lookup "pattern" o of+ Nothing -> pure []+ Just (String p) -> do+ tick+ re <- compilePattern p+ pure (if matchTest re (Text.unpack s) then [] else violation path "pattern" "does not match the pattern")+ Just _ -> unsupported "pattern must be a string"+ pure (lenV <> patV)+ _ -> pure []+ where+ lengthCheck s (k, cmp) = case KeyMap.lookup k o of+ Nothing -> pure []+ Just (Number n) | Right i <- floatingOrInteger @Double n -> do+ tick+ pure (if toInteger (Text.length s) `cmp` i then [] else violation path (Key.toText k) ("violates " <> Key.toText k))+ Just _ -> unsupported (Key.toText k <> " must be an integer")++countKeyword :: KeyMap.KeyMap Value -> Key.Key -> Eval (Maybe Integer)+countKeyword o k = case KeyMap.lookup k o of+ Nothing -> pure Nothing+ Just (Number n) | Right i <- floatingOrInteger @Double n -> pure (Just i)+ Just _ -> unsupported (Key.toText k <> " must be an integer")++arrayKeywords :: Ctx -> Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]+arrayKeywords ctx path o = \case+ Array arr -> do+ let xs = toList arr+ n = toInteger (length xs)+ maxI <- countKeyword o "maxItems"+ minI <- countKeyword o "minItems"+ let sizeV =+ [v | Just m <- [maxI], n > m, v <- violation path "maxItems" "too many items"]+ <> [v | Just m <- [minI], n < m, v <- violation path "minItems" "too few items"]+ uniqV <- case KeyMap.lookup "uniqueItems" o of+ Just (Bool True) -> do+ tick+ if n > 2000 then unsupported "uniqueItems over more than 2000 items is not checked" else pure ()+ pure (if length (nub xs) == length xs then [] else violation path "uniqueItems" "items are not unique")+ _ -> pure []+ prefix <- case KeyMap.lookup "prefixItems" o of+ Nothing -> pure []+ Just (Array ps) -> pure (toList ps)+ Just _ -> unsupported "prefixItems must be an array"+ prefixV <- concat <$> sequence [validate ctx (Text.pack (show i) : path) s x | (i, s, x) <- zip3 [0 :: Int ..] prefix xs]+ itemsV <- case KeyMap.lookup "items" o of+ Nothing -> pure []+ Just (Array _) -> unsupported "array-form items is draft-07 syntax, not 2020-12"+ Just s -> concat <$> sequence [validate ctx (Text.pack (show i) : path) s x | (i, x) <- drop (length prefix) (zip [0 :: Int ..] xs)]+ containsV <- case KeyMap.lookup "contains" o of+ Nothing -> pure []+ Just s -> do+ matches <- length . filter id <$> traverse (\(i, x) -> holds ctx (Text.pack (show i) : path) s x) (zip [0 :: Int ..] xs)+ maxC <- countKeyword o "maxContains"+ minC <- countKeyword o "minContains"+ let lo = maybe 1 id minC+ m = toInteger matches+ pure $+ [v | m < lo, v <- violation path "contains" "too few items match contains"]+ <> [v | Just hi <- [maxC], m > hi, v <- violation path "maxContains" "too many items match contains"]+ pure (sizeV <> uniqV <> prefixV <> itemsV <> containsV)+ _ -> pure []++objectKeywords :: Ctx -> Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]+objectKeywords ctx path o = \case+ Object m -> do+ let names = map Key.toText (KeyMap.keys m)+ n = toInteger (length names)+ maxP <- countKeyword o "maxProperties"+ minP <- countKeyword o "minProperties"+ let sizeV =+ [v | Just x <- [maxP], n > x, v <- violation path "maxProperties" "too many properties"]+ <> [v | Just x <- [minP], n < x, v <- violation path "minProperties" "too few properties"]+ required <- case KeyMap.lookup "required" o of+ Nothing -> pure []+ Just (Array rs) -> traverse (\case String r -> pure r; _ -> unsupported "required entries must be strings") (toList rs)+ Just _ -> unsupported "required must be an array"+ let reqV = concat [violation path "required" ("missing property " <> r) | r <- required, r `notElem` names]+ depReqV <- case KeyMap.lookup "dependentRequired" o of+ Nothing -> pure []+ Just (Object deps) ->+ pure+ [ v+ | (k, Array needs) <- KeyMap.toList deps,+ Key.toText k `elem` names,+ String need <- toList needs,+ need `notElem` names,+ v <- violation path "dependentRequired" ("missing property " <> need)+ ]+ Just _ -> unsupported "dependentRequired must be an object"+ props <- case KeyMap.lookup "properties" o of+ Nothing -> pure KeyMap.empty+ Just (Object ps) -> pure ps+ Just _ -> unsupported "properties must be an object"+ patterns <- case KeyMap.lookup "patternProperties" o of+ Nothing -> pure []+ Just (Object ps) -> traverse (\(k, s) -> (,s) <$> compilePattern (Key.toText k)) (KeyMap.toList ps)+ Just _ -> unsupported "patternProperties must be an object"+ propV <- concat <$> sequence [validate ctx (Key.toText k : path) s v | (k, s) <- KeyMap.toList props, Just v <- [KeyMap.lookup k m]]+ patV <- concat <$> sequence [validate ctx (Key.toText k : path) s v | (k, v) <- KeyMap.toList m, (re, s) <- patterns, matchTest re (Text.unpack (Key.toText k))]+ addV <- case KeyMap.lookup "additionalProperties" o of+ Nothing -> pure []+ Just s ->+ concat+ <$> sequence+ [ validate ctx (Key.toText k : path) s v+ | (k, v) <- KeyMap.toList m,+ not (KeyMap.member k props),+ not (any (\(re, _) -> matchTest re (Text.unpack (Key.toText k))) patterns)+ ]+ namesV <- case KeyMap.lookup "propertyNames" o of+ Nothing -> pure []+ Just s -> concat <$> sequence [validate ctx (nm : path) s (String nm) | nm <- names]+ depSchV <- case KeyMap.lookup "dependentSchemas" o of+ Nothing -> pure []+ Just (Object deps) -> concat <$> sequence [validate ctx path s (Object m) | (k, s) <- KeyMap.toList deps, KeyMap.member k m]+ Just _ -> unsupported "dependentSchemas must be an object"+ pure (sizeV <> reqV <> depReqV <> propV <> patV <> addV <> namesV <> depSchV)+ _ -> pure []++combinators :: Ctx -> Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]+combinators ctx path o inst = do+ allV <- withList "allOf" $ \ss -> concat <$> traverse (\s -> validate ctx path s inst) ss+ anyV <- withList "anyOf" $ \ss -> do+ oks <- traverse (\s -> holds ctx path s inst) ss+ pure (if or oks then [] else violation path "anyOf" "matches none of the alternatives")+ oneV <- withList "oneOf" $ \ss -> do+ oks <- traverse (\s -> holds ctx path s inst) ss+ pure $ case length (filter id oks) of+ 1 -> []+ 0 -> violation path "oneOf" "matches none of the alternatives"+ _ -> violation path "oneOf" "matches more than one alternative"+ notV <- case KeyMap.lookup "not" o of+ Nothing -> pure []+ Just s -> do+ ok <- holds ctx path s inst+ pure (if ok then violation path "not" "matches a forbidden schema" else [])+ condV <- case KeyMap.lookup "if" o of+ Nothing -> pure []+ Just s -> do+ ok <- holds ctx path s inst+ case KeyMap.lookup (if ok then "then" else "else") o of+ Nothing -> pure []+ Just branch -> validate ctx path branch inst+ pure (allV <> anyV <> oneV <> notV <> condV)+ where+ withList k f = case KeyMap.lookup k o of+ Nothing -> pure []+ Just (Array ss) | not (null ss) -> f (toList ss)+ Just _ -> unsupported (Key.toText k <> " must be a non-empty array")++-- ---------------------------------------------------------------------------+-- Patterns++-- | Compile an ECMA-262 pattern when it uses only syntax whose meaning is+-- the same under the POSIX engine used here. Searches, not anchored,+-- exactly as JSON Schema specifies.+compilePattern :: Text -> Eval Regex+compilePattern p = do+ tick+ case translate (Text.unpack p) of+ Left why -> unsupported ("the pattern uses " <> why <> ", which is not supported")+ Right posix -> case makeRegexOptsM (defaultCompOpt {multiline = False}) defaultExecOpt posix of+ Nothing -> unsupported "the pattern could not be parsed"+ Just re -> pure re++translate :: String -> Either Text String+translate = go False+ where+ go _ [] = Right []+ go inClass s = case s of+ ('\\' : c : rest) -> (<>) <$> escape inClass c rest <*> go inClass (dropEscapeTail c rest)+ ('(' : '?' : ':' : rest) | not inClass -> ('(' :) <$> go False rest+ ('(' : '?' : _) | not inClass -> Left "a look-around or named group"+ (q : '?' : rest) | not inClass, q `elem` ("*+?}" :: String) -> (q :) <$> go False rest+ ('.' : rest) | not inClass -> ("[^\n\r\x2028\x2029]" <>) <$> go False rest+ ('[' : rest) | not inClass -> ('[' :) <$> go True rest+ (']' : rest) | inClass -> (']' :) <$> go False rest+ (c : rest) -> (c :) <$> go inClass rest+ dropEscapeTail c rest+ | c == 'u' = drop 4 rest+ | c == 'x' = drop 2 rest+ | otherwise = rest+ classBody c = case c of+ 'd' -> Right "0-9"+ 'w' -> Right "A-Za-z0-9_"+ 's' -> Right " \t\n\r\f\v"+ _ -> Left ""+ escape inClass c rest = case c of+ _ | c `elem` ("dws" :: String) -> fmap (\b -> if inClass then b else "[" <> b <> "]") (classBody c)+ _+ | c `elem` ("DWS" :: String) ->+ if inClass+ then Left "a negated class escape inside brackets"+ else fmap (\b -> "[^" <> b <> "]") (classBody (toLowerAscii c))+ 'n' -> lit inClass '\n'+ 't' -> lit inClass '\t'+ 'r' -> lit inClass '\r'+ 'f' -> lit inClass '\f'+ 'v' -> lit inClass '\v'+ 'u' -> case readHex (take 4 rest) of+ [(n, "")] | length (take 4 rest) == 4 -> lit inClass (chr n)+ _ -> Left "a malformed \\u escape"+ 'x' -> case readHex (take 2 rest) of+ [(n, "")] | length (take 2 rest) == 2 -> lit inClass (chr n)+ _ -> Left "a malformed \\x escape"+ _ | isDigit c -> Left "a back-reference"+ _ | c `elem` ("bBpPkc" :: String) -> Left ("the escape \\" <> Text.singleton c)+ _ -> lit inClass c+ lit inClass ch+ | inClass, ch `elem` ("]-^" :: String) = Left "an escaped bracket, hyphen or caret inside brackets"+ | otherwise = Right (literal inClass ch)+ literal inClass ch+ | inClass = [ch]+ | ch `elem` (".[]()*+?{}|^$\\" :: String) = ['[', ch, ']']+ | otherwise = [ch]+ toLowerAscii ch = if ch >= 'A' && ch <= 'Z' then toEnum (fromEnum ch + 32) else ch
+ src/Baikai/Mcp/Prompt.hs view
@@ -0,0 +1,160 @@+-- | Remote MCP prompts: listing, retrieval and explicit projection into+-- Baikai messages.+--+-- A prompt is a server-provided template of ordered user and assistant+-- messages. Retrieving one performs no other IO: embedded resources and+-- resource links stay data. Projection into Baikai messages is a separate,+-- explicit step that reports every block it cannot represent; a prompt can+-- never become a system instruction through this module.+module Baikai.Mcp.Prompt+ ( -- * Descriptors+ McpPrompt (..),+ PromptArgument (..),++ -- * Listing+ listPrompts,+ listAllPrompts,++ -- * Retrieval+ PromptRole (..),+ PromptMessage (..),+ PromptResult (..),+ PromptError (..),+ getPrompt,+ getPromptMap,++ -- * Projection+ PromptProjection (..),+ projectPromptMessage,+ )+where++import Baikai.Content (ImageContent (..), TextContent (..), UserContent (..))+import Baikai.Mcp.Client+import Baikai.Mcp.Content+import Baikai.Mcp.Protocol+import Baikai.Message (Message (..), UserPayload (..), assistant)+import Data.Aeson (Value (..))+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Object, Parser, withObject, (.:), (.:?))+import Data.ByteString.Base64 qualified as B64+import Data.Foldable (toList)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Text.Encoding qualified as TE+import Data.Vector qualified as Vector+import GHC.Generics (Generic)++data PromptArgument = PromptArgument+ { name :: !Text,+ description :: !(Maybe Text),+ required :: !Bool+ }+ deriving stock (Eq, Show, Generic)++data McpPrompt = McpPrompt+ { name :: !Text,+ title :: !(Maybe Text),+ description :: !(Maybe Text),+ arguments :: ![PromptArgument],+ raw :: !Object+ }+ deriving stock (Eq, Show, Generic)++promptParser :: Value -> Parser McpPrompt+promptParser = withObject "Prompt" $ \o -> do+ args <- fromMaybe [] <$> o .:? "arguments"+ parsedArgs <- traverse argParser args+ McpPrompt <$> o .: "name" <*> o .:? "title" <*> o .:? "description" <*> pure parsedArgs <*> pure o+ where+ argParser = withObject "PromptArgument" $ \a ->+ PromptArgument <$> a .: "name" <*> a .:? "description" <*> (fromMaybe False <$> a .:? "required")++listPrompts :: McpConnection -> Maybe Cursor -> IO (Either McpError (Page McpPrompt))+listPrompts c = requestPage c "prompts/list" "prompts" promptParser++listAllPrompts :: McpConnection -> DrainLimits -> IO (Either (DrainFailure McpError) [McpPrompt])+listAllPrompts c lim = drainPages lim (listPrompts c)++data PromptRole = PromptUser | PromptAssistant+ deriving stock (Eq, Show, Generic)++data PromptMessage = PromptMessage+ { role :: !PromptRole,+ content :: !ContentBlock+ }+ deriving stock (Eq, Show, Generic)++data PromptResult = PromptResult+ { description :: !(Maybe Text),+ -- | In server order.+ messages :: ![PromptMessage],+ continuationRounds :: !Int,+ raw :: !Object+ }+ deriving stock (Eq, Show, Generic)++data PromptError+ = PromptRequestFailed !McpError+ | PromptMalformed !Text+ deriving stock (Eq, Show, Generic)++-- | Retrieve a prompt by its native name with string arguments.+getPrompt :: McpConnection -> Text -> [(Text, Text)] -> IO (Either PromptError (McpOutcome PromptResult))+getPrompt c nm args = getPromptMap c nm (Map.fromList args)++getPromptMap :: McpConnection -> Text -> Map Text Text -> IO (Either PromptError (McpOutcome PromptResult))+getPromptMap c nm args = do+ let params =+ KeyMap.fromList $+ [("name", String nm)]+ <> [("arguments", Object (KeyMap.fromList [(Key.fromText k, String v) | (k, v) <- Map.toList args])) | not (Map.null args)]+ r <- callInteractive c (mcpCall "prompts/get" params)+ pure $ case r of+ Left e -> Left (PromptRequestFailed e)+ Right (McpUnfinished u) -> Right (McpUnfinished u)+ Right (McpCompleted cr) -> McpCompleted <$> decodePrompt cr++decodePrompt :: CompleteResult -> Either PromptError PromptResult+decodePrompt cr = do+ msgs <- case KeyMap.lookup "messages" cr.result of+ Just (Array xs) -> traverse message (toList xs)+ _ -> Left (PromptMalformed "messages must be an array")+ let desc = case KeyMap.lookup "description" cr.result of+ Just (String d) -> Just d+ _ -> Nothing+ Right PromptResult {description = desc, messages = msgs, continuationRounds = cr.continuationRounds, raw = cr.result}+ where+ message = \case+ Object o -> do+ r <- case KeyMap.lookup "role" o of+ Just (String "user") -> Right PromptUser+ Just (String "assistant") -> Right PromptAssistant+ _ -> Left (PromptMalformed "a prompt message has a role other than user or assistant")+ c <- maybe (Left (PromptMalformed "a prompt message has no content")) Right (KeyMap.lookup "content" o)+ Right PromptMessage {role = r, content = decodeContentBlock c}+ _ -> Left (PromptMalformed "a prompt message is not an object")++-- | A prompt message as a Baikai message, or the reason it cannot be one.+data PromptProjection+ = Projected !Message+ | -- | Baikai has no representation for this role and block; the message+ -- is returned unchanged.+ Unprojectable !PromptMessage+ deriving stock (Eq, Show, Generic)++-- | Project user text and images and assistant text. Audio, resources,+-- links, assistant images and unknown blocks are not projected.+projectPromptMessage :: PromptMessage -> PromptProjection+projectPromptMessage m = case (m.role, m.content) of+ (PromptUser, TextBlock t) -> userWith (UserText (TextContent t))+ (PromptUser, ImageBlock d mt) -> case B64.decode (TE.encodeUtf8 d) of+ Right bytes -> userWith (UserImage (ImageContent bytes mt))+ Left _ -> Unprojectable m+ (PromptAssistant, TextBlock t) -> Projected (assistant t)+ _ -> Unprojectable m+ where+ userWith block = Projected (UserMessage UserPayload {content = Vector.singleton block, timestamp = Nothing})
+ src/Baikai/Mcp/Protocol.hs view
@@ -0,0 +1,685 @@+-- | The Model Context Protocol wire vocabulary shared by every feature module.+--+-- This module is pure. It owns the JSON-RPC 2.0 envelope, request+-- identifiers, protocol versions and eras, the per-request @_meta@ fields,+-- result-type discrimination (including interim @input_required@ results),+-- cache hints, opaque pagination cursors and the bounded drain over pages.+-- It does no IO except in 'drainPages', which only sequences a page fetcher+-- the caller supplies.+--+-- Target revision: MCP @2026-07-28@. Earlier revisions are named+-- /legacy/: they open with an @initialize@ handshake and their results carry+-- no @resultType@.+module Baikai.Mcp.Protocol+ ( -- * Protocol versions and eras+ ProtocolVersion (..),+ latestModernVersion,+ modernVersions,+ legacyStreamableVersions,+ httpSseVersions,+ legacyVersions,+ Era (..),+ eraVersion,+ isModern,++ -- * Identities and capabilities+ Implementation (..),+ implementation,+ ServerCapabilities (..),+ capabilityPresent,+ ServerDescription (..),++ -- * Request identifiers and envelopes+ RequestId (..),+ renderRequestId,+ encodeRequest,+ encodeNotification,+ encodeResultResponse,+ encodeErrorResponse,+ IncomingMessage (..),+ decodeMessage,++ -- * Request metadata+ requestMeta,+ withRequestMeta,+ metaProtocolVersion,+ metaClientCapabilities,+ metaClientInfo,+ metaServerInfo,+ metaSubscriptionId,++ -- * Errors reported by the peer+ RpcError (..),+ rpcError,+ parseError,+ invalidRequestCode,+ methodNotFound,+ invalidParams,+ internalError,+ headerMismatch,+ missingRequiredClientCapability,+ unsupportedProtocolVersion,+ legacyResourceNotFound,+ isModernErrorCode,+ unsupportedVersionsOffered,++ -- * Result types+ ResultKind (..),+ decodeResultKind,+ interimMethods,+ supportsInterim,+ InputRequired (..),++ -- * Cache hints+ CacheScope (..),+ CacheHint (..),+ cacheableMethods,+ decodeCacheHint,++ -- * Pagination+ Cursor,+ cursorFromText,+ cursorToText,+ Page (..),+ DrainLimits (..),+ defaultDrainLimits,+ DrainFailure (..),+ drainPages,++ -- * Subscriptions+ SubscriptionFilter (..),+ emptySubscriptionFilter,+ subscriptionNotificationMethods,++ -- * Discovery and handshake results+ decodeDiscoverResult,+ decodeInitializeResult,+ clipText,+ )+where++import Control.Monad (unless, when)+import Data.Aeson (FromJSON (..), ToJSON (..), Value (..), object, withObject, (.:), (.:?), (.=))+import Data.Aeson qualified as Aeson+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap (KeyMap)+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Object, Parser, parseEither)+import Data.ByteString.Lazy qualified as LBS+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe, isNothing)+import Data.Scientific (floatingOrInteger)+import Data.Set qualified as Set+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Time.Clock (NominalDiffTime, diffUTCTime, getCurrentTime)+import GHC.Generics (Generic)++-- ---------------------------------------------------------------------------+-- Versions and eras++-- | A protocol revision name such as @2026-07-28@.+newtype ProtocolVersion = ProtocolVersion {versionText :: Text}+ deriving stock (Eq, Ord, Show, Generic)+ deriving newtype (ToJSON, FromJSON)++-- | The revision this client targets.+latestModernVersion :: ProtocolVersion+latestModernVersion = ProtocolVersion "2026-07-28"++-- | Modern revisions this client implements, most preferred first. Modern+-- revisions carry version and capabilities on every request.+modernVersions :: [ProtocolVersion]+modernVersions = [latestModernVersion]++-- | Handshake-era revisions spoken over Streamable HTTP, most preferred first.+legacyStreamableVersions :: [ProtocolVersion]+legacyStreamableVersions = map ProtocolVersion ["2025-11-25", "2025-06-18", "2025-03-26"]++-- | Revisions spoken over the deprecated two-endpoint HTTP+SSE transport.+httpSseVersions :: [ProtocolVersion]+httpSseVersions = [ProtocolVersion "2024-11-05"]++-- | Every handshake-era revision this client accepts from @initialize@.+legacyVersions :: [ProtocolVersion]+legacyVersions = legacyStreamableVersions <> httpSseVersions++-- | Which generation of the protocol a connection speaks. The era is a+-- property of the server and is fixed for the life of a connection.+data Era+ = -- | Per-request metadata, no handshake, no session.+ Modern ProtocolVersion+ | -- | @initialize@ handshake at the negotiated version.+ Legacy ProtocolVersion+ deriving stock (Eq, Show, Generic)++eraVersion :: Era -> ProtocolVersion+eraVersion = \case+ Modern v -> v+ Legacy v -> v++isModern :: Era -> Bool+isModern = \case+ Modern _ -> True+ Legacy _ -> False++-- ---------------------------------------------------------------------------+-- Identities++-- | A self-reported implementation identity (@clientInfo@ / @serverInfo@).+-- Display and logging only; never a basis for security decisions.+data Implementation = Implementation+ { name :: !Text,+ version :: !Text,+ title :: !(Maybe Text)+ }+ deriving stock (Eq, Show, Generic)++implementation :: Text -> Text -> Implementation+implementation n v = Implementation {name = n, version = v, title = Nothing}++instance ToJSON Implementation where+ toJSON i =+ object $+ ["name" .= i.name, "version" .= i.version]+ <> maybe [] (\t -> ["title" .= t]) i.title++instance FromJSON Implementation where+ parseJSON = withObject "Implementation" $ \o ->+ Implementation <$> o .: "name" <*> o .: "version" <*> o .:? "title"++-- | Server capabilities, kept as the raw object the server sent so that+-- capabilities this client does not model are not lost.+newtype ServerCapabilities = ServerCapabilities {raw :: Object}+ deriving stock (Eq, Show, Generic)++instance FromJSON ServerCapabilities where+ parseJSON = withObject "ServerCapabilities" (pure . ServerCapabilities)++-- | Whether the server advertised a top-level capability such as @tools@.+capabilityPresent :: Text -> ServerCapabilities -> Bool+capabilityPresent k caps = case KeyMap.lookup (Key.fromText k) caps.raw of+ Nothing -> False+ Just Null -> False+ Just _ -> True++-- | What a server said about itself when the connection was opened, from+-- @server/discover@ (modern) or @initialize@ (legacy).+data ServerDescription = ServerDescription+ { era :: !Era,+ supportedVersions :: ![ProtocolVersion],+ capabilities :: !ServerCapabilities,+ serverInfo :: !(Maybe Implementation),+ instructions :: !(Maybe Text),+ cache :: !(Maybe CacheHint)+ }+ deriving stock (Eq, Show, Generic)++-- ---------------------------------------------------------------------------+-- Request identifiers and envelopes++-- | A JSON-RPC request identifier. Never null.+data RequestId+ = RequestIdNumber !Integer+ | RequestIdText !Text+ deriving stock (Eq, Ord, Show, Generic)++instance ToJSON RequestId where+ toJSON = \case+ RequestIdNumber n -> toJSON n+ RequestIdText t -> toJSON t++instance FromJSON RequestId where+ parseJSON = \case+ String t -> pure (RequestIdText t)+ Number n -> case floatingOrInteger @Double n of+ Right i -> pure (RequestIdNumber i)+ Left _ -> fail "request id must be an integer or a string"+ _ -> fail "request id must be an integer or a string"++renderRequestId :: RequestId -> Text+renderRequestId = \case+ RequestIdNumber n -> Text.pack (show n)+ RequestIdText t -> clipText 64 t++-- | A request envelope. @params@ is omitted when empty.+encodeRequest :: RequestId -> Text -> Object -> Value+encodeRequest rid method params =+ Object . KeyMap.fromList $+ [("jsonrpc", String "2.0"), ("id", toJSON rid), ("method", String method)]+ <> [("params", Object params) | not (KeyMap.null params)]++-- | A notification envelope (no identifier).+encodeNotification :: Text -> Object -> Value+encodeNotification method params =+ Object . KeyMap.fromList $+ [("jsonrpc", String "2.0"), ("method", String method)]+ <> [("params", Object params) | not (KeyMap.null params)]++-- | A response to a request the server sent (legacy profiles only).+encodeResultResponse :: RequestId -> Object -> Value+encodeResultResponse rid result =+ object ["jsonrpc" .= ("2.0" :: Text), "id" .= rid, "result" .= result]++encodeErrorResponse :: RequestId -> RpcError -> Value+encodeErrorResponse rid err =+ object ["jsonrpc" .= ("2.0" :: Text), "id" .= rid, "error" .= err]++-- | A message received from a server.+data IncomingMessage+ = -- | A response. The identifier is absent only on an error response+ -- to a request the server could not read.+ IncomingResponse !(Maybe RequestId) !(Either RpcError Object)+ | IncomingNotification !Text !Object+ | -- | A server-initiated request. Only legacy profiles permit these.+ IncomingRequest !RequestId !Text !Object+ deriving stock (Eq, Show, Generic)++-- | Decode one JSON-RPC 2.0 message. Rejects a wrong or missing @jsonrpc@+-- member, a frame with both @result@ and @error@, a null request+-- identifier and a non-object @params@ or @result@.+decodeMessage :: Value -> Either Text IncomingMessage+decodeMessage = first' . parseEither parser+ where+ first' = either (Left . clipText 200 . Text.pack) Right+ parser = withObject "JSON-RPC message" $ \o -> do+ v <- o .:? "jsonrpc"+ unless (v == Just ("2.0" :: Text)) (fail "jsonrpc member must be \"2.0\"")+ let has k = KeyMap.member k o+ case (has "method", has "result", has "error") of+ (True, False, False) -> do+ method <- o .: "method"+ params <- fromMaybe KeyMap.empty <$> o .:? "params"+ case KeyMap.lookup "id" o of+ Nothing -> pure (IncomingNotification method params)+ Just Null -> fail "request id must not be null"+ Just idv -> do+ rid <- parseJSON idv+ pure (IncomingRequest rid method params)+ (False, True, False) -> do+ rid <- responseId o+ case rid of+ Nothing -> fail "a result response must carry an id"+ Just _ -> pure ()+ r <- o .: "result"+ pure (IncomingResponse rid (Right r))+ (False, False, True) -> do+ rid <- responseId o+ e <- o .: "error"+ pure (IncomingResponse rid (Left e))+ (False, True, True) -> fail "a response must not carry both result and error"+ _ -> fail "not a JSON-RPC request, notification or response"+ responseId o = case KeyMap.lookup "id" o of+ Nothing -> pure Nothing+ Just Null -> pure Nothing+ Just idv -> Just <$> parseJSON idv++-- ---------------------------------------------------------------------------+-- Request metadata++metaProtocolVersion, metaClientCapabilities, metaClientInfo, metaServerInfo, metaSubscriptionId :: Aeson.Key+metaProtocolVersion = "io.modelcontextprotocol/protocolVersion"+metaClientCapabilities = "io.modelcontextprotocol/clientCapabilities"+metaClientInfo = "io.modelcontextprotocol/clientInfo"+metaServerInfo = "io.modelcontextprotocol/serverInfo"+metaSubscriptionId = "io.modelcontextprotocol/subscriptionId"++-- | The per-request protocol fields of a modern request. The client+-- advertises no capabilities: it answers no sampling, elicitation or roots+-- requests.+requestMeta :: ProtocolVersion -> Maybe Implementation -> Object+requestMeta v info =+ KeyMap.fromList $+ [ (metaProtocolVersion, toJSON v),+ (metaClientCapabilities, Object KeyMap.empty)+ ]+ <> maybe [] (\i -> [(metaClientInfo, toJSON i)]) info++-- | Merge the protocol fields into @params._meta@. Protocol fields win over+-- any same-named key the caller supplied.+withRequestMeta :: Object -> Object -> Object+withRequestMeta meta params =+ let existing = case KeyMap.lookup "_meta" params of+ Just (Object m) -> m+ _ -> KeyMap.empty+ in KeyMap.insert "_meta" (Object (meta <> existing)) params++-- ---------------------------------------------------------------------------+-- Peer errors++-- | A JSON-RPC error object reported by the server. The message is clipped+-- and oversized @data@ is dropped on decoding, so the value is safe to+-- render.+data RpcError = RpcError+ { code :: !Int,+ message :: !Text,+ errorData :: !(Maybe Value)+ }+ deriving stock (Eq, Show, Generic)++rpcError :: Int -> Text -> RpcError+rpcError c m = RpcError {code = c, message = m, errorData = Nothing}++instance FromJSON RpcError where+ parseJSON = withObject "JSON-RPC error" $ \o -> do+ c <- o .: "code"+ m <- fromMaybe "" <$> o .:? "message"+ d <- o .:? "data"+ let bounded = case d of+ Just v | LBS.length (Aeson.encode v) <= 8192 -> Just v+ _ -> Nothing+ pure RpcError {code = c, message = clipText 512 m, errorData = bounded}++instance ToJSON RpcError where+ toJSON e =+ object $+ ["code" .= e.code, "message" .= e.message]+ <> maybe [] (\d -> ["data" .= d]) e.errorData++parseError, invalidRequestCode, methodNotFound, invalidParams, internalError :: Int+parseError = -32700+invalidRequestCode = -32600+methodNotFound = -32601+invalidParams = -32602+internalError = -32603++-- | Modern error codes defined by the 2026-07-28 revision.+headerMismatch, missingRequiredClientCapability, unsupportedProtocolVersion :: Int+headerMismatch = -32020+missingRequiredClientCapability = -32021+unsupportedProtocolVersion = -32022++-- | Resource-not-found code used by 2025-11-25 and earlier.+legacyResourceNotFound :: Int+legacyResourceNotFound = -32002++-- | Whether an error code identifies a modern server.+isModernErrorCode :: Int -> Bool+isModernErrorCode c = c `elem` [headerMismatch, missingRequiredClientCapability, unsupportedProtocolVersion]++-- | The versions an @UnsupportedProtocolVersionError@ lists, when the+-- error is one and its data is well formed.+unsupportedVersionsOffered :: RpcError -> Maybe [ProtocolVersion]+unsupportedVersionsOffered e+ | e.code /= unsupportedProtocolVersion = Nothing+ | otherwise = case e.errorData of+ Just (Object d) | Just v <- KeyMap.lookup "supported" d -> either (const Nothing) Just (parseEither parseJSON v)+ _ -> Nothing++-- ---------------------------------------------------------------------------+-- Result types++-- | The two result types defined by the core protocol.+data ResultKind+ = ResultComplete+ | ResultInputRequired !InputRequired+ deriving stock (Eq, Show, Generic)++-- | An interim result: the server needs more before it can finish.+data InputRequired = InputRequired+ { -- | Requests the server wants the client to answer (sampling,+ -- elicitation, roots), keyed by server-assigned identifiers. This+ -- client advertises none of those capabilities and never answers them.+ inputRequests :: !(Maybe (Map Text Value)),+ -- | Opaque state to echo byte for byte on a retry.+ requestState :: !(Maybe Text)+ }+ deriving stock (Eq, Show, Generic)++-- | Methods on which a server may return an interim result.+interimMethods :: [Text]+interimMethods = ["tools/call", "resources/read", "prompts/get"]++supportsInterim :: Text -> Bool+supportsInterim m = m `elem` interimMethods++-- | Discriminate a result object. An absent @resultType@ is @complete@+-- (earlier revisions omit it); an unknown one is invalid; an interim+-- result must carry @inputRequests@, @requestState@ or both, and is only+-- valid for 'interimMethods'.+decodeResultKind :: Text -> Object -> Either Text ResultKind+decodeResultKind method o = case KeyMap.lookup "resultType" o of+ Nothing -> Right ResultComplete+ Just (String "complete") -> Right ResultComplete+ Just (String "input_required")+ | not (supportsInterim method) ->+ Left ("the server returned an input_required result for " <> method <> ", which does not allow one")+ | otherwise -> do+ reqs <- case KeyMap.lookup "inputRequests" o of+ Nothing -> Right Nothing+ Just Null -> Right Nothing+ Just (Object m)+ | KeyMap.null m -> Right Nothing+ | otherwise -> Right (Just (Map.fromList [(Key.toText k, v) | (k, v) <- KeyMap.toList m]))+ Just _ -> Left "inputRequests must be an object"+ st <- case KeyMap.lookup "requestState" o of+ Nothing -> Right Nothing+ Just Null -> Right Nothing+ Just (String s) -> Right (Just s)+ Just _ -> Left "requestState must be a string"+ when (isNothing reqs && isNothing st) $+ Left "an input_required result must carry inputRequests or requestState"+ Right (ResultInputRequired InputRequired {inputRequests = reqs, requestState = st})+ Just (String other) -> Left ("unsupported resultType " <> clipText 64 other)+ Just _ -> Left "resultType must be a string"++-- ---------------------------------------------------------------------------+-- Cache hints++data CacheScope = CachePublic | CachePrivate+ deriving stock (Eq, Show, Generic)++-- | A freshness hint. Returned to the caller; this package keeps no cache.+data CacheHint = CacheHint+ { -- | Milliseconds the result may be considered fresh. Negative values+ -- from the server are clamped to zero.+ ttlMs :: !Integer,+ scope :: !CacheScope+ }+ deriving stock (Eq, Show, Generic)++-- | Methods whose complete results carry cache hints.+cacheableMethods :: [Text]+cacheableMethods =+ ["server/discover", "tools/list", "prompts/list", "resources/list", "resources/templates/list", "resources/read"]++-- | Read @ttlMs@ and @cacheScope@. Both absent is 'Nothing' (earlier+-- revisions omit them). A present but ill-typed field, an unknown scope,+-- or only one of the two is an error.+decodeCacheHint :: Object -> Either Text (Maybe CacheHint)+decodeCacheHint o = case (KeyMap.lookup "ttlMs" o, KeyMap.lookup "cacheScope" o) of+ (Nothing, Nothing) -> Right Nothing+ (Just (Number n), Just (String s)) -> do+ ttl <- case floatingOrInteger @Double n of+ Right i -> Right (max 0 i)+ Left _ -> Left "ttlMs must be an integer"+ sc <- case s of+ "public" -> Right CachePublic+ "private" -> Right CachePrivate+ _ -> Left "cacheScope must be \"public\" or \"private\""+ Right (Just CacheHint {ttlMs = ttl, scope = sc})+ (Just _, Just _) -> Left "ttlMs must be a number and cacheScope a string"+ _ -> Left "ttlMs and cacheScope must appear together"++-- ---------------------------------------------------------------------------+-- Pagination++-- | An opaque pagination cursor. Never parsed or modified; an empty string+-- is a valid cursor.+newtype Cursor = Cursor Text+ deriving stock (Eq, Ord, Generic)++instance Show Cursor where+ show (Cursor t) = "Cursor " <> show (clipText 32 t)++cursorFromText :: Text -> Cursor+cursorFromText = Cursor++cursorToText :: Cursor -> Text+cursorToText (Cursor t) = t++-- | One page of a list result.+data Page a = Page+ { items :: ![a],+ nextCursor :: !(Maybe Cursor),+ cache :: !(Maybe CacheHint),+ -- | Size of the response that carried the page, for byte budgets.+ responseBytes :: !Int+ }+ deriving stock (Eq, Show, Generic, Functor)++-- | Ceilings for draining every page of a list.+data DrainLimits = DrainLimits+ { maxPages :: !Int,+ maxItems :: !Int,+ maxBytes :: !Int,+ -- | Wall-clock budget for the whole drain.+ maxElapsed :: !NominalDiffTime+ }+ deriving stock (Eq, Show, Generic)++defaultDrainLimits :: DrainLimits+defaultDrainLimits = DrainLimits {maxPages = 32, maxItems = 4096, maxBytes = 16 * 1024 * 1024, maxElapsed = 120}++-- | Why a drain stopped early. @e@ is the page fetcher's own error.+data DrainFailure e+ = DrainPageFailed !Int !e+ | DrainRepeatedCursor !Int+ | DrainTooManyPages !Int+ | DrainTooManyItems !Int+ | DrainTooManyBytes !Int+ | DrainDeadline !Int+ deriving stock (Eq, Show, Generic)++-- | Fetch pages until one has no @nextCursor@, preserving order. Stops,+-- discarding what was collected, on the first fetch error, a cursor seen+-- before, or when a limit would be exceeded. Page and deadline limits are+-- checked /before/ a fetch, so no request is sent past them.+drainPages :: DrainLimits -> (Maybe Cursor -> IO (Either e (Page a))) -> IO (Either (DrainFailure e) [a])+drainPages lim fetch = do+ start <- getCurrentTime+ let go n seen cursor itemCount byteCount acc+ | n >= lim.maxPages = pure (Left (DrainTooManyPages n))+ | otherwise = do+ now <- getCurrentTime+ if diffUTCTime now start > lim.maxElapsed+ then pure (Left (DrainDeadline n))+ else do+ r <- fetch cursor+ case r of+ Left e -> pure (Left (DrainPageFailed (n + 1) e))+ Right page -> do+ let items' = itemCount + length page.items+ bytes' = byteCount + page.responseBytes+ acc' = page.items : acc+ if+ | items' > lim.maxItems -> pure (Left (DrainTooManyItems items'))+ | bytes' > lim.maxBytes -> pure (Left (DrainTooManyBytes bytes'))+ | otherwise -> case page.nextCursor of+ Nothing -> pure (Right (concat (reverse acc')))+ Just c+ | Set.member c seen -> pure (Left (DrainRepeatedCursor (n + 1)))+ | otherwise -> go (n + 1) (Set.insert c seen) (Just c) items' bytes' acc'+ go 0 Set.empty Nothing 0 0 []++-- ---------------------------------------------------------------------------+-- Subscriptions++-- | Which change notifications a @subscriptions/listen@ stream carries.+data SubscriptionFilter = SubscriptionFilter+ { toolsListChanged :: !Bool,+ promptsListChanged :: !Bool,+ resourcesListChanged :: !Bool,+ resourceSubscriptions :: ![Text]+ }+ deriving stock (Eq, Show, Generic)++emptySubscriptionFilter :: SubscriptionFilter+emptySubscriptionFilter = SubscriptionFilter False False False []++instance ToJSON SubscriptionFilter where+ toJSON f =+ object $+ ["toolsListChanged" .= True | f.toolsListChanged]+ <> ["promptsListChanged" .= True | f.promptsListChanged]+ <> ["resourcesListChanged" .= True | f.resourcesListChanged]+ <> ["resourceSubscriptions" .= f.resourceSubscriptions | not (null f.resourceSubscriptions)]++instance FromJSON SubscriptionFilter where+ parseJSON = withObject "SubscriptionFilter" $ \o ->+ SubscriptionFilter+ <$> (fromMaybe False <$> o .:? "toolsListChanged")+ <*> (fromMaybe False <$> o .:? "promptsListChanged")+ <*> (fromMaybe False <$> o .:? "resourcesListChanged")+ <*> (fromMaybe [] <$> o .:? "resourceSubscriptions")++-- | The notification methods a filter admits.+subscriptionNotificationMethods :: SubscriptionFilter -> [Text]+subscriptionNotificationMethods f =+ ["notifications/tools/list_changed" | f.toolsListChanged]+ <> ["notifications/prompts/list_changed" | f.promptsListChanged]+ <> ["notifications/resources/list_changed" | f.resourcesListChanged]+ <> ["notifications/resources/updated" | not (null f.resourceSubscriptions)]++-- ---------------------------------------------------------------------------+-- Discovery and handshake++-- | Decode a @server/discover@ result.+decodeDiscoverResult :: Object -> Either Text ServerDescription+decodeDiscoverResult o = do+ (vs, caps, info, instr) <- mapLeft' $ parseEither p o+ hint <- decodeCacheHint o+ when (null vs) (Left "supportedVersions is empty")+ Right+ ServerDescription+ { era = Modern latestModernVersion,+ supportedVersions = vs,+ capabilities = caps,+ serverInfo = info,+ instructions = instr,+ cache = hint+ }+ where+ p obj = do+ vs <- obj .: "supportedVersions"+ caps <- fromMaybe (ServerCapabilities KeyMap.empty) <$> obj .:? "capabilities"+ info <- resultServerInfo obj+ instr <- obj .:? "instructions"+ pure (vs :: [ProtocolVersion], caps, info, instr)++-- | Decode an @initialize@ result into the negotiated version and server+-- description. The caller checks the version against its allowlist.+decodeInitializeResult :: Object -> Either Text (ProtocolVersion, ServerDescription)+decodeInitializeResult o = mapLeft' $ flip parseEither o $ \obj -> do+ v <- obj .: "protocolVersion"+ caps <- fromMaybe (ServerCapabilities KeyMap.empty) <$> obj .:? "capabilities"+ info <- obj .:? "serverInfo"+ instr <- obj .:? "instructions"+ pure+ ( v,+ ServerDescription+ { era = Legacy v,+ supportedVersions = [v],+ capabilities = caps,+ serverInfo = info,+ instructions = instr,+ cache = Nothing+ }+ )++resultServerInfo :: Object -> Parser (Maybe Implementation)+resultServerInfo obj = do+ meta <- obj .:? "_meta"+ case meta of+ Just (m :: KeyMap Value) | Just v <- KeyMap.lookup metaServerInfo m -> Just <$> parseJSON v+ _ -> pure Nothing++mapLeft' :: Either String a -> Either Text a+mapLeft' = either (Left . clipText 200 . Text.pack) Right++-- | Truncate text to a character budget, marking the cut.+clipText :: Int -> Text -> Text+clipText n t+ | Text.length t <= n = t+ | otherwise = Text.take n t <> "…"
+ src/Baikai/Mcp/Resource.hs view
@@ -0,0 +1,231 @@+-- | Remote MCP resources: listing, templates, reads and optional change+-- notifications.+--+-- A resource is identified by a URI, which is not assumed to be a file+-- path. A read returns every content item the server sent, each with its+-- own URI and MIME type, as text or decoded bytes. The application decides+-- what to read and whether any of it enters a model's context; nothing+-- here follows a link or reads a URI on its own.+module Baikai.Mcp.Resource+ ( -- * Descriptors+ McpResource (..),+ McpResourceTemplate (..),++ -- * Listing+ listResources,+ listAllResources,+ listResourceTemplates,+ listAllResourceTemplates,++ -- * Reading+ ResourceContents (..),+ ResourceBody (..),+ ResourceRead (..),+ ReadOptions (..),+ defaultReadOptions,+ ResourceError (..),+ readResource,+ readResourceWith,++ -- * Change notifications+ ResourceEvent (..),+ withResourceUpdates,+ nextResourceEvent,+ )+where++import Baikai.Mcp.Client+import Baikai.Mcp.Protocol+import Data.Aeson (Value (..))+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Object, Parser, withObject, (.:), (.:?))+import Data.ByteString (ByteString)+import Data.ByteString.Base64 qualified as B64+import Data.Foldable (toList)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.Encoding qualified as TE+import GHC.Generics (Generic)++-- ---------------------------------------------------------------------------+-- Descriptors++data McpResource = McpResource+ { uri :: !Text,+ name :: !Text,+ title :: !(Maybe Text),+ description :: !(Maybe Text),+ mimeType :: !(Maybe Text),+ size :: !(Maybe Integer),+ raw :: !Object+ }+ deriving stock (Eq, Show, Generic)++-- | A family of resources addressed by an RFC 6570 URI template.+data McpResourceTemplate = McpResourceTemplate+ { uriTemplate :: !Text,+ name :: !Text,+ title :: !(Maybe Text),+ description :: !(Maybe Text),+ mimeType :: !(Maybe Text),+ raw :: !Object+ }+ deriving stock (Eq, Show, Generic)++resourceParser :: Value -> Parser McpResource+resourceParser = withObject "Resource" $ \o ->+ McpResource+ <$> o .: "uri"+ <*> o .: "name"+ <*> o .:? "title"+ <*> o .:? "description"+ <*> o .:? "mimeType"+ <*> o .:? "size"+ <*> pure o++templateParser :: Value -> Parser McpResourceTemplate+templateParser = withObject "ResourceTemplate" $ \o ->+ McpResourceTemplate+ <$> o .: "uriTemplate"+ <*> o .: "name"+ <*> o .:? "title"+ <*> o .:? "description"+ <*> o .:? "mimeType"+ <*> pure o++-- ---------------------------------------------------------------------------+-- Listing++-- | One page of @resources/list@.+listResources :: McpConnection -> Maybe Cursor -> IO (Either McpError (Page McpResource))+listResources c = requestPage c "resources/list" "resources" resourceParser++listAllResources :: McpConnection -> DrainLimits -> IO (Either (DrainFailure McpError) [McpResource])+listAllResources c lim = drainPages lim (listResources c)++-- | One page of @resources/templates/list@.+listResourceTemplates :: McpConnection -> Maybe Cursor -> IO (Either McpError (Page McpResourceTemplate))+listResourceTemplates c = requestPage c "resources/templates/list" "resourceTemplates" templateParser++listAllResourceTemplates :: McpConnection -> DrainLimits -> IO (Either (DrainFailure McpError) [McpResourceTemplate])+listAllResourceTemplates c lim = drainPages lim (listResourceTemplates c)++-- ---------------------------------------------------------------------------+-- Reading++-- | One item of a read: its own URI and MIME type and either text or+-- decoded bytes.+data ResourceContents = ResourceContents+ { uri :: !Text,+ mimeType :: !(Maybe Text),+ body :: !ResourceBody,+ raw :: !Object+ }+ deriving stock (Eq, Show, Generic)++data ResourceBody+ = TextBody !Text+ | BlobBody !ByteString+ deriving stock (Eq, Show, Generic)++data ResourceRead = ResourceRead+ { -- | Every item, in server order. May be empty for an existing+ -- resource with no content.+ contents :: ![ResourceContents],+ -- | 'Nothing' for a result reached through continuation rounds.+ cache :: !(Maybe CacheHint),+ continuationRounds :: !Int,+ raw :: !Object+ }+ deriving stock (Eq, Show, Generic)++newtype ReadOptions = ReadOptions+ { -- | Refuse a blob whose Base64 text is longer than this, before+ -- decoding it.+ maxBlobChars :: Int+ }++defaultReadOptions :: ReadOptions+defaultReadOptions = ReadOptions {maxBlobChars = 8 * 1024 * 1024}++data ResourceError+ = -- | The server reported that the resource does not exist (@-32602@+ -- naming the URI, or the historical @-32002@).+ ResourceNotFound !McpError+ | ResourceRequestFailed !McpError+ | -- | The result is not a readable resource result.+ ResourceMalformed !Text+ deriving stock (Eq, Show, Generic)++readResource :: McpConnection -> Text -> IO (Either ResourceError (McpOutcome ResourceRead))+readResource c = readResourceWith c defaultReadOptions++-- | Read one URI. A state-only interim result is continued by the client.+readResourceWith :: McpConnection -> ReadOptions -> Text -> IO (Either ResourceError (McpOutcome ResourceRead))+readResourceWith c opts target = do+ r <- callInteractive c (mcpCall "resources/read" (KeyMap.singleton "uri" (String target)))+ pure $ case r of+ Left e+ | notFound e -> Left (ResourceNotFound e)+ | otherwise -> Left (ResourceRequestFailed e)+ Right (McpUnfinished u) -> Right (McpUnfinished u)+ Right (McpCompleted cr) -> McpCompleted <$> decodeRead opts cr+ where+ notFound e = case e.rpc of+ Just err+ | err.code == legacyResourceNotFound -> True+ | err.code == invalidParams -> case err.errorData of+ Just (Object d) -> KeyMap.lookup "uri" d == Just (String target)+ _ -> False+ _ -> False++decodeRead :: ReadOptions -> CompleteResult -> Either ResourceError ResourceRead+decodeRead opts cr = do+ items <- case KeyMap.lookup "contents" cr.result of+ Just (Array xs) -> traverse item (toList xs)+ _ -> Left (ResourceMalformed "contents must be an array")+ Right ResourceRead {contents = items, cache = cr.cache, continuationRounds = cr.continuationRounds, raw = cr.result}+ where+ item = \case+ Object o -> do+ u <- case KeyMap.lookup "uri" o of+ Just (String s) -> Right s+ _ -> Left (ResourceMalformed "a content item has no uri")+ let mt = case KeyMap.lookup "mimeType" o of+ Just (String m) -> Just m+ _ -> Nothing+ case (KeyMap.lookup "text" o, KeyMap.lookup "blob" o) of+ (Just (String t), Nothing) -> Right ResourceContents {uri = u, mimeType = mt, body = TextBody t, raw = o}+ (Nothing, Just (String b))+ | Text.length b > opts.maxBlobChars -> Left (ResourceMalformed "a blob exceeds the configured size limit")+ | otherwise -> case B64.decode (TE.encodeUtf8 b) of+ Right bs -> Right ResourceContents {uri = u, mimeType = mt, body = BlobBody bs, raw = o}+ Left _ -> Left (ResourceMalformed "a blob is not valid Base64")+ _ -> Left (ResourceMalformed "a content item must carry exactly one of text and blob")+ _ -> Left (ResourceMalformed "a content item is not an object")++-- ---------------------------------------------------------------------------+-- Change notifications++data ResourceEvent+ = -- | A subscribed resource changed; read it again when appropriate.+ ResourceUpdated !Text+ | ResourceListChanged+ | ResourceStreamEnded !SubscriptionEnd+ deriving stock (Eq, Show, Generic)++-- | Listen for updates to the given URIs and, optionally, list changes,+-- on a modern connection. The acknowledged filter may be a subset.+withResourceUpdates :: McpConnection -> [Text] -> Bool -> (Subscription -> IO a) -> IO (Either McpError a)+withResourceUpdates c uris listChanges =+ withSubscription c emptySubscriptionFilter {resourceSubscriptions = uris, resourcesListChanged = listChanges}++nextResourceEvent :: Subscription -> IO ResourceEvent+nextResourceEvent s = do+ ev <- nextSubscriptionEvent s+ case ev of+ SubscriptionNotification "notifications/resources/updated" p+ | Just (String u) <- KeyMap.lookup "uri" p -> pure (ResourceUpdated u)+ SubscriptionNotification "notifications/resources/list_changed" _ -> pure ResourceListChanged+ SubscriptionNotification _ _ -> nextResourceEvent s+ SubscriptionEnded e -> pure (ResourceStreamEnded e)
+ src/Baikai/Mcp/Tool.hs view
@@ -0,0 +1,445 @@+-- | Remote MCP tools: discovery, descriptor-bound invocation and rich+-- results.+--+-- A discovered 'McpTool' keeps the server's native name, its input schema+-- exactly as sent, an optional output schema and every other field. A call+-- binds one such descriptor ('McpToolCall'), so the parameter headers+-- mirrored on the wire and the output contract checked afterwards come+-- from the schema the host approved — never from a list fetched later.+--+-- Four outcomes stay distinct: a completed result (which may itself report+-- a tool failure through @isError@), an unfinished interim result returned+-- by "Baikai.Mcp.Client", a refusal or transport failure whose 'Delivery'+-- says whether the tool may have run, and a descriptor-drift rejection+-- (@-32020@) that the host resolves by listing tools again. Nothing here+-- retries a call or swaps a descriptor.+module Baikai.Mcp.Tool+ ( -- * Descriptors+ McpTool (..),+ HeaderMirror (..),+ RejectedTool (..),+ decodeTool,+ toBaikaiTool,++ -- * Discovery+ ToolPage (..),+ listToolsPage,+ ToolListing (..),+ listTools,++ -- * Invocation+ McpToolCall (..),+ mcpToolCall,+ ContentBlock (..),+ StructuredContent (..),+ OutputCheck (..),+ McpToolResult (..),+ McpToolError (..),+ callTool,+ callToolWith,+ CallToolOptions (..),+ defaultCallToolOptions,++ -- * Projection into Baikai messages+ ToolResultProjection (..),+ projectToolResult,+ toolResultMessageFor,++ -- * Change notifications+ ToolListChange (..),+ withToolListChanges,+ nextToolListChange,+ )+where++import Baikai.Content (ImageContent (..), TextContent (..), ToolResultContent (..))+import Baikai.Mcp.Client+import Baikai.Mcp.Content+import Baikai.Mcp.JsonSchema+import Baikai.Mcp.Protocol+import Baikai.Mcp.Transport (ParamHeader, paramHeader, validParamName)+import Baikai.Message (Message, ToolResult (..), toolResultMessage)+import Baikai.Tool (Tool, mkTool)+import Data.Aeson (Value (..))+import Data.Aeson qualified as Aeson+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Object)+import Data.ByteString.Base64 qualified as B64+import Data.ByteString.Lazy qualified as LBS+import Data.Char (toLower)+import Data.Foldable (toList)+import Data.List (nub)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.Encoding qualified as TE+import Data.Vector qualified as Vector+import GHC.Generics (Generic)++-- ---------------------------------------------------------------------------+-- Descriptors++-- | A validated @x-mcp-header@ annotation: the header name portion and the+-- chain of property names leading to the annotated argument.+data HeaderMirror = HeaderMirror+ { headerName :: !Text,+ propertyPath :: ![Text]+ }+ deriving stock (Eq, Show, Generic)++-- | A tool as the server described it.+data McpTool = McpTool+ { -- | The server's own name, sent verbatim on invocation.+ name :: !Text,+ title :: !(Maybe Text),+ description :: !(Maybe Text),+ -- | The input JSON Schema, unchanged.+ inputSchema :: !Value,+ -- | The output JSON Schema, of any root type, when declared.+ outputSchema :: !(Maybe Value),+ annotations :: !(Maybe Object),+ -- | Parameter mirrors this connection must send (modern HTTP only).+ headerMirrors :: ![HeaderMirror],+ -- | The descriptor object as received.+ raw :: !Object+ }+ deriving stock (Eq, Show, Generic)++-- | A descriptor left out of a listing, and why.+data RejectedTool = RejectedTool+ { toolName :: !(Maybe Text),+ reason :: !Text+ }+ deriving stock (Eq, Show, Generic)++-- | Decode a descriptor. With @checkMirrors@ (modern Streamable HTTP) the+-- @x-mcp-header@ annotations are validated and a tool with an invalid one+-- is rejected; on other bindings they are ignored, as the specification+-- allows.+decodeTool :: Bool -> Value -> Either RejectedTool McpTool+decodeTool checkMirrors = \case+ Object o -> do+ nm <- case KeyMap.lookup "name" o of+ Just (String n) | not (Text.null n) -> Right n+ _ -> Left (RejectedTool Nothing "the descriptor has no name")+ let reject :: forall a. Text -> Either RejectedTool a+ reject why = Left (RejectedTool (Just nm) why)+ optText k = case KeyMap.lookup k o of+ Just (String t) -> Right (Just t)+ Nothing -> Right Nothing+ Just Null -> Right Nothing+ Just _ -> reject (Key.toText k <> " must be a string")+ ttl <- optText "title"+ desc <- optText "description"+ input <- case KeyMap.lookup "inputSchema" o of+ Just s@(Object so) -> case KeyMap.lookup "type" so of+ Just (String "object") -> Right s+ _ -> reject "inputSchema must have type \"object\""+ _ -> reject "inputSchema must be an object"+ output <- case KeyMap.lookup "outputSchema" o of+ Nothing -> Right Nothing+ Just Null -> Right Nothing+ Just s@(Object _) -> Right (Just s)+ Just s@(Bool _) -> Right (Just s)+ Just _ -> reject "outputSchema must be a schema"+ anns <- case KeyMap.lookup "annotations" o of+ Just (Object a) -> Right (Just a)+ Nothing -> Right Nothing+ Just Null -> Right Nothing+ Just _ -> reject "annotations must be an object"+ mirrors <-+ if checkMirrors+ then either reject Right (headerMirrorsOf input)+ else Right []+ Right+ McpTool+ { name = nm,+ title = ttl,+ description = desc,+ inputSchema = input,+ outputSchema = output,+ annotations = anns,+ headerMirrors = mirrors,+ raw = o+ }+ _ -> Left (RejectedTool Nothing "the descriptor is not an object")++-- | Find and validate every @x-mcp-header@ in an input schema. An+-- annotation is valid only where a chain of @properties@ keys reaches it+-- from the root, on a property typed @string@, @integer@ or @boolean@,+-- with a valid and case-insensitively unique token.+headerMirrorsOf :: Value -> Either Text [HeaderMirror]+headerMirrorsOf schema = do+ found <- walk True [] schema+ let lowered = map (Text.map toLower . (.headerName)) found+ if length (nub lowered) /= length lowered+ then Left "x-mcp-header names are not case-insensitively unique"+ else Right found+ where+ -- @static@: reached from the root through properties keys only.+ walk :: Bool -> [Text] -> Value -> Either Text [HeaderMirror]+ walk static path = \case+ Object o -> do+ here <- case KeyMap.lookup "x-mcp-header" o of+ Nothing -> Right []+ Just ann+ | not static || null path -> Left "x-mcp-header is not on a statically reachable property"+ | otherwise -> do+ hname <- case ann of+ String h | validParamName h -> Right h+ _ -> Left "an x-mcp-header value is not a valid HTTP token"+ case KeyMap.lookup "type" o of+ Just (String t) | t `elem` ["string", "integer", "boolean"] -> Right ()+ _ -> Left ("x-mcp-header " <> hname <> " is on a property that is not a string, integer or boolean")+ Right [HeaderMirror {headerName = hname, propertyPath = reverse path}]+ nested <- fmap concat . traverse (descend o) $ KeyMap.toList o+ Right (here <> nested)+ Array xs -> concat <$> traverse (walk False path) (toList xs)+ _ -> Right []+ where+ descend _ (k, v) = case Key.toText k of+ "x-mcp-header" -> Right []+ "properties" -> case v of+ Object props -> concat <$> traverse (\(pk, ps) -> walk static (Key.toText pk : path) ps) (KeyMap.toList props)+ _ -> walk False path v+ _ -> walk False path v++-- | The model-facing tool. The input schema is passed through verbatim;+-- only the description is defaulted (to the title, else empty).+toBaikaiTool :: McpTool -> Tool+toBaikaiTool t = mkTool t.name (fromMaybe (fromMaybe "" t.title) t.description) t.inputSchema++-- ---------------------------------------------------------------------------+-- Discovery++-- | One @tools/list@ page and the descriptors excluded from it.+data ToolPage = ToolPage+ { page :: !(Page McpTool),+ rejected :: ![RejectedTool]+ }+ deriving stock (Eq, Show, Generic)++checksMirrors :: McpConnection -> Bool+checksMirrors c = isModern (connectionEra c) && connectionBindingShape c == RequestScopedHttp++-- | Request one page. The host's hook sees the cursor of every page after+-- the first and may refuse it before anything is sent.+listToolsPage :: McpConnection -> Maybe Cursor -> IO (Either McpError ToolPage)+listToolsPage c cur = do+ r <- requestPage c "tools/list" "tools" (pure . decodeTool (checksMirrors c)) cur+ pure $ flip fmap r $ \p ->+ ToolPage+ { page = p {items = [t | Right t <- p.items]},+ rejected = [x | Left x <- p.items]+ }++-- | Every tool, in server order, under the drain's ceilings.+data ToolListing = ToolListing+ { tools :: ![McpTool],+ rejected :: ![RejectedTool]+ }+ deriving stock (Eq, Show, Generic)++-- | List all pages. A failure, a repeated cursor or an exceeded limit+-- discards the partial listing.+listTools :: McpConnection -> DrainLimits -> IO (Either (DrainFailure McpError) ToolListing)+listTools c lim = do+ r <- drainPages lim $ \cur -> do+ p <- listToolsPage c cur+ pure $ flip fmap p $ \tp -> tp.page {items = map Right tp.page.items <> map Left tp.rejected}+ pure $ flip fmap r $ \xs -> ToolListing {tools = [t | Right t <- xs], rejected = [x | Left x <- xs]}++-- ---------------------------------------------------------------------------+-- Results++-- | Structured content keeps a present @null@ distinct from absence.+data StructuredContent+ = NoStructuredContent+ | StructuredContent !Value+ deriving stock (Eq, Show, Generic)++-- | What was established about the structured result.+data OutputCheck+ = -- | The tool declares no output schema.+ NoOutputSchema+ | OutputConforms+ | -- | The tool reported an execution error; no contract applies.+ NotCheckedToolError+ deriving stock (Eq, Show, Generic)++data McpToolResult = McpToolResult+ { content :: ![ContentBlock],+ structured :: !StructuredContent,+ isError :: !Bool,+ outputCheck :: !OutputCheck,+ -- | The result object as received.+ raw :: !Object,+ continuationRounds :: !Int+ }+ deriving stock (Eq, Show, Generic)++data McpToolError+ = -- | The request failed; 'Delivery' says whether the tool may have run.+ ToolRequestFailed !McpError+ | -- | The server rejected the call's routing headers (@-32020@) before+ -- running it, usually because the tool's schema changed. List tools+ -- again and decide whether the new descriptor is still approved.+ ToolDescriptorDrift !McpError+ | -- | The arguments cannot be mirrored into the headers the descriptor+ -- requires. Nothing was sent.+ ToolArgumentsUnmirrorable !Text+ | -- | The tool ran, but its structured output breaks the declared+ -- contract. The result is kept for inspection.+ ToolOutputViolatesSchema ![SchemaViolation] !McpToolResult+ | -- | The tool ran, but its output contract could not be checked: the+ -- schema uses unsupported features or exceeds the evaluation budget,+ -- or structured content is missing.+ ToolOutputUnverifiable !Text !McpToolResult+ | -- | The result is not a tool result.+ ToolResultMalformed !Text+ deriving stock (Eq, Show, Generic)++-- ---------------------------------------------------------------------------+-- Invocation++-- | A call bound to the descriptor it was approved against.+data McpToolCall = McpToolCall+ { tool :: !McpTool,+ arguments :: !Object+ }+ deriving stock (Eq, Show, Generic)++mcpToolCall :: McpTool -> Object -> McpToolCall+mcpToolCall t args = McpToolCall {tool = t, arguments = args}++data CallToolOptions = CallToolOptions+ { schemaBudget :: !SchemaBudget,+ -- | Receives request-scoped notifications such as progress.+ onNotification :: !(Maybe (Text -> Object -> IO ()))+ }++defaultCallToolOptions :: CallToolOptions+defaultCallToolOptions = CallToolOptions {schemaBudget = defaultSchemaBudget, onNotification = Nothing}++callTool :: McpConnection -> McpToolCall -> IO (Either McpToolError (McpOutcome McpToolResult))+callTool c = callToolWith c defaultCallToolOptions++-- | Invoke a bound tool. A state-only interim result is continued by the+-- client with the same name, arguments and header mirrors on every round.+callToolWith :: McpConnection -> CallToolOptions -> McpToolCall -> IO (Either McpToolError (McpOutcome McpToolResult))+callToolWith c opts call = case mirrorHeaders of+ Left why -> pure (Left (ToolArgumentsUnmirrorable why))+ Right hs -> do+ let params = KeyMap.fromList [("name", String call.tool.name), ("arguments", Object call.arguments)]+ req = (mcpCall "tools/call" params) {paramHeaders = hs, onNotification = opts.onNotification}+ r <- callInteractive c req+ pure $ case r of+ Left e+ | fmap (.code) e.rpc == Just headerMismatch -> Left (ToolDescriptorDrift e)+ | otherwise -> Left (ToolRequestFailed e)+ Right (McpUnfinished u) -> Right (McpUnfinished u)+ Right (McpCompleted cr) -> McpCompleted <$> interpret opts call.tool cr+ where+ mirrorHeaders :: Either Text [ParamHeader]+ mirrorHeaders+ | not (checksMirrors c) = Right []+ | otherwise = fmap concat . traverse mirror $ call.tool.headerMirrors+ mirror m = maybe [] pure <$> paramHeader m.headerName (lookupPath m.propertyPath (Object call.arguments))+ lookupPath [] v = Just v+ lookupPath (k : ks) (Object o) = KeyMap.lookup (Key.fromText k) o >>= lookupPath ks+ lookupPath _ _ = Nothing++interpret :: CallToolOptions -> McpTool -> CompleteResult -> Either McpToolError McpToolResult+interpret opts t cr = do+ blocks <- case KeyMap.lookup "content" cr.result of+ Just (Array xs) -> Right (map decodeContentBlock (toList xs))+ Nothing -> Right []+ Just _ -> Left (ToolResultMalformed "content must be an array")+ err <- case KeyMap.lookup "isError" cr.result of+ Nothing -> Right False+ Just (Bool b) -> Right b+ Just _ -> Left (ToolResultMalformed "isError must be a boolean")+ let structured = maybe NoStructuredContent StructuredContent (KeyMap.lookup "structuredContent" cr.result)+ base =+ McpToolResult+ { content = blocks,+ structured = structured,+ isError = err,+ outputCheck = NoOutputSchema,+ raw = cr.result,+ continuationRounds = cr.continuationRounds+ }+ case (err, t.outputSchema) of+ (True, _) -> Right base {outputCheck = NotCheckedToolError}+ (False, Nothing) -> Right base+ (False, Just schema) -> case structured of+ NoStructuredContent -> Left (ToolOutputUnverifiable "the tool declares an output schema but returned no structured content" base)+ StructuredContent v -> case validateJson opts.schemaBudget schema v of+ Conforms -> Right base {outputCheck = OutputConforms}+ Violates vs -> Left (ToolOutputViolatesSchema vs base)+ Unverifiable why -> Left (ToolOutputUnverifiable why base)++-- ---------------------------------------------------------------------------+-- Projection++-- | A tool result as a Baikai tool result, with what could not be carried.+data ToolResultProjection = ToolResultProjection+ { toolResult :: !ToolResult,+ -- | Blocks Baikai's tool results cannot represent (audio, resources,+ -- unknown types, undecodable images). Never silently dropped.+ unprojected :: ![ContentBlock]+ }+ deriving stock (Eq, Show, Generic)++-- | Project text and images. When the result has no content blocks but+-- carries structured content, that content is rendered as one JSON text+-- block, as the specification asks servers to do themselves.+projectToolResult :: McpToolResult -> ToolResultProjection+projectToolResult r =+ ToolResultProjection+ { toolResult = ToolResult {content = Vector.fromList (projected <> structuredText), isError = r.isError},+ unprojected = [b | (b, Nothing) <- zip r.content (map project r.content)]+ }+ where+ projected = [x | Just x <- map project r.content]+ structuredText = case (r.content, r.structured) of+ ([], StructuredContent v) -> [ToolResultText (TextContent (TE.decodeUtf8 (LBS.toStrict (Aeson.encode v))))]+ _ -> []+ project = \case+ TextBlock t -> Just (ToolResultText (TextContent t))+ ImageBlock d m -> case B64.decode (TE.encodeUtf8 d) of+ Right bytes -> Just (ToolResultImage (ImageContent bytes m))+ Left _ -> Nothing+ _ -> Nothing++-- | The tool-result message answering a model's tool call. The caller+-- supplies the model's tool-call identifier and the name the model used.+toolResultMessageFor :: Text -> Text -> McpToolResult -> (Message, [ContentBlock])+toolResultMessageFor callId modelName r =+ let p = projectToolResult r+ in (toolResultMessage callId modelName p.toolResult, p.unprojected)++-- ---------------------------------------------------------------------------+-- Change notifications++data ToolListChange+ = -- | The server reported that its tool list changed. Nothing has been+ -- fetched; list again when the owner decides to.+ ToolListChanged+ | ToolListStreamEnded !SubscriptionEnd+ deriving stock (Eq, Show, Generic)++-- | Listen for @notifications/tools/list_changed@ on a modern connection.+-- The action receives the subscription; the acknowledged filter says+-- whether the server agreed to send tool changes at all.+withToolListChanges :: McpConnection -> (Subscription -> IO a) -> IO (Either McpError a)+withToolListChanges c = withSubscription c emptySubscriptionFilter {toolsListChanged = True}++nextToolListChange :: Subscription -> IO ToolListChange+nextToolListChange s = do+ ev <- nextSubscriptionEvent s+ case ev of+ SubscriptionNotification "notifications/tools/list_changed" _ -> pure ToolListChanged+ SubscriptionNotification _ _ -> nextToolListChange s+ SubscriptionEnded e -> pure (ToolListStreamEnded e)
+ src/Baikai/Mcp/Transport.hs view
@@ -0,0 +1,356 @@+-- | Streamable HTTP framing: routing headers, the Base64 header sentinel,+-- parameter mirrors and the request-scoped HTTP binding.+--+-- Every modern request is its own @POST@. The reply is one JSON object or+-- a Server-Sent Events stream scoped to that request; notifications on the+-- stream precede the correlated response. Closing the response cancels the+-- request, so no @notifications/cancelled@ is ever sent over HTTP. The+-- binding never follows a redirect: the endpoint the host authorized is the+-- only one that receives its credentials.+module Baikai.Mcp.Transport+ ( -- * Header values+ encodeHeaderValue,+ decodeHeaderValue,++ -- * Routing headers+ hProtocolVersion,+ hMcpMethod,+ hMcpName,+ hSessionId,+ isProtocolControlledHeader,+ routingName,++ -- * Parameter mirrors+ ParamHeader,+ paramHeader,+ paramHeaderField,+ paramHeaderValue,+ validParamName,+ jsSafeIntegerBound,++ -- * The Streamable HTTP binding+ streamableHttpBinding,+ )+where++import Baikai.Mcp.Error+import Baikai.Mcp.Internal.Binding+import Baikai.Mcp.Internal.Http+import Baikai.Mcp.Internal.Sse (SseEvent (..))+import Baikai.Mcp.Protocol+import Control.Exception (SomeException, try)+import Data.Aeson (Value (..))+import Data.Aeson qualified as Aeson+import Data.Aeson.KeyMap qualified as KeyMap+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Base64 qualified as B64+import Data.ByteString.Char8 qualified as BS8+import Data.CaseInsensitive qualified as CI+import Data.Char (isAlphaNum, isAscii, ord)+import Data.IORef+import Data.Scientific (floatingOrInteger)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.Encoding qualified as TE+import Network.HTTP.Client qualified as HTTP+import Network.HTTP.Types (Header, HeaderName, hAccept, hContentType)++-- ---------------------------------------------------------------------------+-- Header values++sentinelPrefix, sentinelSuffix :: Text+sentinelPrefix = "=?base64?"+sentinelSuffix = "?="++-- | Encode a value for an @Mcp-Name@ or @Mcp-Param-*@ header. A value that+-- is not plain visible ASCII, has leading or trailing whitespace, or+-- already looks like the sentinel is sent as+-- @=?base64?{Base64 of UTF-8}?=@.+encodeHeaderValue :: Text -> ByteString+encodeHeaderValue t+ | plain = TE.encodeUtf8 t+ | otherwise = TE.encodeUtf8 sentinelPrefix <> B64.encode (TE.encodeUtf8 t) <> TE.encodeUtf8 sentinelSuffix+ where+ plain =+ Text.all safeChar t+ && not (edgeSpace (Text.take 1 t))+ && not (edgeSpace (Text.takeEnd 1 t))+ && not (Text.isPrefixOf sentinelPrefix t && Text.isSuffixOf sentinelSuffix t)+ safeChar c = isAscii c && ((ord c >= 0x20 && ord c <= 0x7E) || c == '\t')+ edgeSpace s = s == " " || s == "\t"++-- | The inverse of 'encodeHeaderValue', as a server validating mirrors+-- would apply it.+decodeHeaderValue :: ByteString -> Either Text Text+decodeHeaderValue raw =+ case TE.decodeUtf8' raw of+ Left _ -> Left "header value is not UTF-8"+ Right t+ | Text.isPrefixOf sentinelPrefix t,+ Text.isSuffixOf sentinelSuffix t,+ Text.length t >= Text.length sentinelPrefix + Text.length sentinelSuffix ->+ let inner = Text.dropEnd (Text.length sentinelSuffix) (Text.drop (Text.length sentinelPrefix) t)+ in case B64.decode (TE.encodeUtf8 inner) of+ Left _ -> Left "invalid Base64 in a sentinel-encoded header"+ Right bytes -> either (const (Left "sentinel-encoded header is not UTF-8")) Right (TE.decodeUtf8' bytes)+ | otherwise -> Right t++-- ---------------------------------------------------------------------------+-- Routing headers++hProtocolVersion, hMcpMethod, hMcpName, hSessionId :: HeaderName+hProtocolVersion = "MCP-Protocol-Version"+hMcpMethod = "Mcp-Method"+hMcpName = "Mcp-Name"+hSessionId = "Mcp-Session-Id"++-- | Headers this package sets itself. A request hook may not supply them.+isProtocolControlledHeader :: HeaderName -> Bool+isProtocolControlledHeader n =+ n+ `elem` [ hProtocolVersion,+ hMcpMethod,+ hMcpName,+ hSessionId,+ hContentType,+ hAccept,+ "Content-Length",+ "Transfer-Encoding",+ "Host",+ "Connection",+ "Last-Event-ID"+ ]+ || BS.isPrefixOf "mcp-" (CI.foldedCase n)++-- | The value mirrored into @Mcp-Name@: the tool or prompt name, or the+-- resource URI, for the three methods that require it.+routingName :: Text -> KeyMap.KeyMap Value -> Maybe Text+routingName method params = case method of+ "tools/call" -> str "name"+ "prompts/get" -> str "name"+ "resources/read" -> str "uri"+ _ -> Nothing+ where+ str k = case KeyMap.lookup k params of+ Just (String s) -> Just s+ _ -> Nothing++-- ---------------------------------------------------------------------------+-- Parameter mirrors++-- | A validated @Mcp-Param-{Name}@ header. Built only by 'paramHeader'.+data ParamHeader = ParamHeader {field :: !HeaderName, value :: !ByteString}+ deriving stock (Eq, Show)++paramHeaderField :: ParamHeader -> HeaderName+paramHeaderField p = p.field++paramHeaderValue :: ParamHeader -> ByteString+paramHeaderValue p = p.value++-- | Whether an @x-mcp-header@ value is a valid HTTP field-name token.+validParamName :: Text -> Bool+validParamName t = not (Text.null t) && Text.all tchar t+ where+ tchar c = isAscii c && (isAlphaNum c || c `elem` ("!#$%&'*+-.^_`|~" :: String))++-- | The largest integer a mirror may carry: 2^53 - 1.+jsSafeIntegerBound :: Integer+jsSafeIntegerBound = 2 ^ (53 :: Int) - 1++-- | Mirror one argument value. 'Nothing' for an absent or null value, which+-- must not be mirrored. Strings, booleans and safe integers are encoded;+-- any other value is refused rather than sent unmirrored.+paramHeader :: Text -> Maybe Value -> Either Text (Maybe ParamHeader)+paramHeader nm mv+ | not (validParamName nm) = Left ("x-mcp-header name " <> clipText 64 nm <> " is not a valid HTTP token")+ | otherwise = case mv of+ Nothing -> Right Nothing+ Just Null -> Right Nothing+ Just (String s) -> mk (encodeHeaderValue s)+ Just (Bool b) -> mk (if b then "true" else "false")+ Just (Number n) -> case floatingOrInteger @Double n of+ Right i+ | abs i <= jsSafeIntegerBound -> mk (BS8.pack (show i))+ | otherwise -> Left ("the value mirrored to " <> nm <> " is outside the safe integer range")+ Left _ -> Left ("the value mirrored to " <> nm <> " is not an integer")+ Just _ -> Left ("the value mirrored to " <> nm <> " is not a string, integer or boolean")+ where+ mk v = Right (Just ParamHeader {field = CI.mk ("Mcp-Param-" <> TE.encodeUtf8 nm), value = v})++-- ---------------------------------------------------------------------------+-- The binding++-- | The request-scoped Streamable HTTP binding, for both the modern+-- revision and handshake-era revisions (which add a session header).+streamableHttpBinding :: HTTP.Manager -> HttpEndpoint -> Binding+streamableHttpBinding mgr ep =+ Binding+ { shape = RequestScopedHttp,+ endpointText = ep.rendered,+ origin = ep.origin,+ exchange = httpExchange mgr ep,+ post = httpPost mgr ep,+ openStream = Just (httpOpenStream mgr ep),+ terminate = Just (httpDelete mgr ep),+ release = pure (),+ unsolicited = Nothing+ }++baseRequest :: HttpEndpoint -> HTTP.Request+baseRequest ep =+ ep.request+ { HTTP.redirectCount = 0,+ HTTP.responseTimeout = HTTP.responseTimeoutNone,+ HTTP.checkResponse = \_ _ -> pure ()+ }++postRequest :: HttpEndpoint -> [Header] -> BS.ByteString -> HTTP.Request+postRequest ep hdrs body =+ (baseRequest ep)+ { HTTP.method = "POST",+ HTTP.requestHeaders =+ [ (hContentType, "application/json"),+ (hAccept, "application/json, text/event-stream")+ ]+ <> hdrs,+ HTTP.requestBody = HTTP.RequestBodyBS body+ }++httpExchange :: HTTP.Manager -> HttpEndpoint -> WireLimits -> Exchange -> IO (Either McpError Reply)+httpExchange mgr ep lim ex =+ withOpened mgr (postRequest ep ex.headers ex.body) $ \resp ->+ readReply lim ex resp++-- | Interpret the response to one request.+readReply :: WireLimits -> Exchange -> HTTP.Response HTTP.BodyReader -> IO (Either McpError Reply)+readReply lim ex resp+ | st == 401 || st == 403 = do+ _ <- readBounded 65536 (HTTP.responseBody resp)+ pure . Left $+ (mcpError HttpFailure Answered (if st == 401 then "the server requires authorization" else "the server refused the credentials"))+ { httpStatus = Just st,+ challenge = TE.decodeUtf8Lenient <$> responseHeader "WWW-Authenticate" resp+ }+ | st >= 300 && st < 400 = pure . Left $ (mcpError HttpFailure Answered "the server answered with a redirect, which is not followed") {httpStatus = Just st}+ | st >= 200 && st < 300, contentType resp == Just "text/event-stream" = readStream+ | st >= 200 && st < 300 = do+ b <- readBounded lim.maxResponseBytes (HTTP.responseBody resp)+ case b of+ Left _ -> pure (Left (mcpError LimitExceeded Uncertain "the response exceeded the configured size limit"))+ Right bytes+ | BS.null bytes -> pure (Left ((mcpError MalformedReply Uncertain "the server returned no response to a request") {httpStatus = Just st}))+ | otherwise -> pure (decodeReply bytes)+ | otherwise = do+ b <- readBounded (min lim.maxResponseBytes 1048576) (HTTP.responseBody resp)+ pure $ case b of+ Right bytes+ | Right (IncomingResponse rid (Left e)) <- decodeFrame bytes,+ maybe True (== ex.requestId) rid ->+ Right Reply {outcome = Left e, bytes = BS.length bytes, status = Just st, sessionId = session}+ _ -> Left ((mcpError HttpFailure Answered ("the server answered HTTP " <> Text.pack (show st))) {httpStatus = Just st})+ where+ st = statusOf resp+ session = responseHeader hSessionId resp+ decodeReply bytes = case decodeFrame bytes of+ Left why -> Left ((mcpError MalformedReply Uncertain why) {httpStatus = Just st})+ Right (IncomingResponse rid r)+ | rid == Just ex.requestId || (rid == Nothing && isLeft' r) ->+ Right Reply {outcome = r, bytes = BS.length bytes, status = Just st, sessionId = session}+ | otherwise -> Left ((mcpError MalformedReply Uncertain "the response carries an unrelated request id") {httpStatus = Just st})+ Right _ -> Left ((mcpError MalformedReply Uncertain "the server returned a message that is not a response") {httpStatus = Just st})+ readStream = do+ reader <- newEventReader lim.maxFrameBytes (Just lim.maxResponseBytes) (HTTP.responseBody resp)+ let loop = do+ ev <- nextEvent reader+ case ev of+ Left e -> pure (Left e {httpStatus = Just st})+ Right Nothing -> pure (Left ((mcpError TransportFailure Uncertain "the response stream ended before the reply") {httpStatus = Just st}))+ Right (Just e)+ | e.eventName /= "" && e.eventName /= "message" -> loop+ | otherwise -> case decodeFrame e.eventData of+ Left why -> pure (Left ((mcpError MalformedReply Uncertain why) {httpStatus = Just st}))+ Right (IncomingNotification m p) -> ex.onNotification m p >> loop+ Right (IncomingRequest rid m p) -> ex.onServerRequest rid m p >> loop+ Right (IncomingResponse rid r)+ | rid == Just ex.requestId -> do+ n <- eventReaderBytes reader+ pure (Right Reply {outcome = r, bytes = n, status = Just st, sessionId = session})+ | otherwise -> pure (Left ((mcpError MalformedReply Uncertain "the stream carried a response to an unrelated request id") {httpStatus = Just st}))+ loop+ isLeft' = either (const True) (const False)++decodeFrame :: ByteString -> Either Text IncomingMessage+decodeFrame bytes = case Aeson.eitherDecodeStrict bytes of+ Left _ -> Left "the server sent a message that is not valid JSON"+ Right v -> decodeMessage v++httpPost :: HTTP.Manager -> HttpEndpoint -> [Header] -> BS.ByteString -> IO (Either McpError ())+httpPost mgr ep hdrs body =+ withOpened mgr (postRequest ep hdrs body) $ \resp -> do+ _ <- readBounded 65536 (HTTP.responseBody resp)+ let st = statusOf resp+ pure $+ if st >= 200 && st < 300+ then Right ()+ else Left ((mcpError HttpFailure Answered ("the server answered HTTP " <> Text.pack (show st) <> " to a notification")) {httpStatus = Just st})++-- | Open a long-lived response stream for @subscriptions/listen@. The+-- caller owns the stream and must 'close' it.+httpOpenStream :: HTTP.Manager -> HttpEndpoint -> WireLimits -> Exchange -> IO (Either McpError MessageStream)+httpOpenStream mgr ep lim ex = do+ opened <- openResponse mgr (postRequest ep ex.headers ex.body)+ case opened of+ Left e -> pure (Left e)+ Right resp+ | statusOf resp >= 200 && statusOf resp < 300 && contentType resp == Just "text/event-stream" -> do+ reader <- newEventReader lim.maxFrameBytes Nothing (HTTP.responseBody resp)+ closed <- newIORef False+ let close = do+ was <- atomicModifyIORef' closed (True,)+ if was then pure () else HTTP.responseClose resp+ next = do+ isClosed <- readIORef closed+ if isClosed+ then pure (StreamEnded Nothing)+ else do+ r <- tryRead (nextEvent reader)+ case r of+ Left e -> pure (StreamEnded (Just e))+ Right (Left e) -> pure (StreamEnded (Just e))+ Right (Right Nothing) -> pure (StreamEnded Nothing)+ Right (Right (Just e))+ | e.eventName /= "" && e.eventName /= "message" -> next+ | otherwise -> case decodeFrame e.eventData of+ Left why -> pure (StreamEnded (Just (mcpError MalformedReply Uncertain why)))+ Right m -> pure (StreamMessage m)+ pure (Right MessageStream {next = next, close = close})+ | otherwise -> do+ r <- readReply lim ex resp+ HTTP.responseClose resp+ case r of+ Left e -> pure (Left e)+ Right reply -> do+ delivered <- newIORef False+ let next = do+ was <- atomicModifyIORef' delivered (True,)+ pure $+ if was+ then StreamEnded Nothing+ else StreamMessage (IncomingResponse (Just ex.requestId) reply.outcome)+ pure (Right MessageStream {next = next, close = pure ()})+ where+ tryRead act = do+ r <- try @SomeException act+ case r of+ Left e -> rethrowAsync e >> pure (Left (bodyFailure e))+ Right v -> pure (Right v)++httpDelete :: HTTP.Manager -> HttpEndpoint -> [Header] -> IO ()+httpDelete mgr ep hdrs = do+ _ <-+ withOpened mgr ((baseRequest ep) {HTTP.method = "DELETE", HTTP.requestHeaders = hdrs}) $ \resp -> do+ _ <- readBounded 65536 (HTTP.responseBody resp)+ pure (Right ())+ pure ()
+ src/Baikai/Mcp/Transport/HttpSse.hs view
@@ -0,0 +1,178 @@+-- | The deprecated two-endpoint HTTP+SSE transport of revision+-- @2024-11-05@.+--+-- The client opens one long-lived @GET@ event stream. Its first event,+-- @endpoint@, names the URL to which the client @POST@s every message; the+-- server answers each @POST@ with @202 Accepted@ and delivers the actual+-- replies as @message@ events on the @GET@ stream.+--+-- MCP @2026-07-28@ lists this transport as Deprecated and eligible for+-- removal three months after its feature lifecycle policy becomes final.+-- It is selected only by explicit configuration and lives in this one+-- module so that it can be removed without touching any other profile.+--+-- The advertised message endpoint must have the same origin as the+-- configured endpoint. Otherwise the connection is refused before anything+-- — in particular a credential — is sent to it.+module Baikai.Mcp.Transport.HttpSse+ ( openHttpSseBinding,+ )+where++import Baikai.Mcp.Error+import Baikai.Mcp.Internal.Binding+import Baikai.Mcp.Internal.Http+import Baikai.Mcp.Internal.Mux qualified as Mux+import Baikai.Mcp.Internal.Sse (SseEvent (..))+import Baikai.Mcp.Protocol+import Control.Concurrent.Async (async, cancel)+import Control.Exception (SomeException, finally, mask, onException, try)+import Data.Aeson qualified as Aeson+import Data.ByteString qualified as BS+import Data.IORef+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.Encoding qualified as TE+import Network.HTTP.Client qualified as HTTP+import Network.HTTP.Types (Header, hAccept, hContentType)+import Network.URI (parseURIReference, relativeTo)+import System.Timeout (timeout)++-- | Open the event stream with the given (hook-approved) headers, wait at+-- most @waitMicros@ for the @endpoint@ event and return a multiplexed+-- binding. @postHeaders@ supplies the headers each later @POST@ carries+-- beyond those the client passes per exchange.+openHttpSseBinding :: HTTP.Manager -> HttpEndpoint -> WireLimits -> Int -> [Header] -> IO (Either McpError Binding)+openHttpSseBinding mgr ep lim waitMicros hdrs = mask $ \restore -> do+ let getReq =+ ep.request+ { HTTP.method = "GET",+ HTTP.redirectCount = 0,+ HTTP.responseTimeout = HTTP.responseTimeoutNone,+ HTTP.checkResponse = \_ _ -> pure (),+ HTTP.requestHeaders = (hAccept, "text/event-stream") : hdrs+ }+ opened <- restore (openResponse mgr getReq)+ case opened of+ Left e -> pure (Left e)+ Right resp -> do+ let closeResp = HTTP.responseClose resp+ r <- restore (handshake resp) `onException` closeResp+ case r of+ Left e -> closeResp >> pure (Left e)+ Right (reader, messageEp) -> do+ handlerRef <- newIORef (\_ _ _ -> pure ())+ mux <- Mux.newMux (\rid m p -> readIORef handlerRef >>= \h -> h rid m p)+ readerThread <- async (restore (readLoop reader mux) `finally` closeResp)+ released <- newIORef False+ let release = do+ was <- atomicModifyIORef' released (True,)+ if was then pure () else cancel readerThread+ pure . Right $+ Binding+ { shape = MultiplexedHttp,+ endpointText = ep.rendered,+ origin = ep.origin,+ exchange = sseExchange mgr messageEp mux,+ post = ssePost mgr messageEp,+ openStream = Nothing,+ terminate = Nothing,+ release = release,+ unsolicited = Just handlerRef+ }+ where+ handshake resp+ | statusOf resp == 401 || statusOf resp == 403 =+ pure . Left $+ (mcpError HttpFailure Answered "the server requires authorization for its event stream")+ { httpStatus = Just (statusOf resp),+ challenge = TE.decodeUtf8Lenient <$> responseHeader "WWW-Authenticate" resp+ }+ | statusOf resp /= 200 || contentType resp /= Just "text/event-stream" =+ pure . Left $+ (mcpError HttpFailure Answered "the endpoint did not open an HTTP+SSE event stream")+ { httpStatus = Just (statusOf resp)+ }+ | otherwise = do+ reader <- newEventReader lim.maxFrameBytes Nothing (HTTP.responseBody resp)+ first <- timeout waitMicros (nextEvent reader)+ pure $ case first of+ Nothing -> Left (mcpError TimedOut NotSent "the event stream sent no endpoint event in time")+ Just (Left e) -> Left e {delivery = NotSent}+ Just (Right Nothing) -> Left (mcpError TransportFailure NotSent "the event stream ended before its endpoint event")+ Just (Right (Just ev))+ | ev.eventName /= "endpoint" -> Left (mcpError MalformedReply NotSent "the event stream did not begin with an endpoint event")+ | otherwise -> (reader,) <$> resolveMessageEndpoint ep (TE.decodeUtf8Lenient ev.eventData)++-- | Resolve the advertised endpoint against the configured one and insist+-- on the same origin.+resolveMessageEndpoint :: HttpEndpoint -> Text -> Either McpError HttpEndpoint+resolveMessageEndpoint ep advertised = do+ let base = HTTP.getUri ep.request+ ref <- maybe (Left bad) Right (parseURIReference (Text.unpack (Text.strip advertised)))+ let resolved = ref `relativeTo` base+ target <- either (const (Left bad)) Right (parseEndpoint (Text.pack (show resolved)))+ if sameOrigin target ep+ then Right target+ else Left (mcpError IncompatibleServer NotSent "the server advertised a message endpoint on a different origin; refusing to send to it")+ where+ bad = mcpError MalformedReply NotSent "the server advertised an unusable message endpoint"++readLoop :: EventReader -> Mux.Mux -> IO ()+readLoop reader mux = do+ r <- try @SomeException loop+ case r of+ Left e -> Mux.failAll mux (bodyFailure e)+ Right () -> pure ()+ where+ loop = do+ ev <- nextEvent reader+ case ev of+ Left e -> Mux.failAll mux e+ Right Nothing -> Mux.failAll mux (mcpError TransportFailure Uncertain "the server closed the event stream")+ Right (Just e)+ | e.eventName /= "" && e.eventName /= "message" -> loop+ | otherwise -> case Aeson.eitherDecodeStrict e.eventData >>= either (Left . Text.unpack) Right . decodeMessage of+ Left _ -> Mux.failAll mux (mcpError MalformedReply Uncertain "the server sent an unreadable message on the event stream")+ Right msg -> Mux.dispatch mux (BS.length e.eventData) msg >> loop++messageRequest :: HttpEndpoint -> [Header] -> BS.ByteString -> HTTP.Request+messageRequest ep hdrs body =+ ep.request+ { HTTP.method = "POST",+ HTTP.redirectCount = 0,+ HTTP.responseTimeout = HTTP.responseTimeoutNone,+ HTTP.checkResponse = \_ _ -> pure (),+ HTTP.requestHeaders = (hContentType, "application/json") : hdrs,+ HTTP.requestBody = HTTP.RequestBodyBS body+ }++ssePost :: HTTP.Manager -> HttpEndpoint -> [Header] -> BS.ByteString -> IO (Either McpError ())+ssePost mgr ep hdrs body =+ withOpened mgr (messageRequest ep hdrs body) $ \resp -> do+ _ <- readBounded 65536 (HTTP.responseBody resp)+ let st = statusOf resp+ pure $+ if st >= 200 && st < 300+ then Right ()+ else+ Left+ ( (mcpError HttpFailure Answered ("the message endpoint answered HTTP " <> Text.pack (show st)))+ { httpStatus = Just st,+ challenge = TE.decodeUtf8Lenient <$> responseHeader "WWW-Authenticate" resp+ }+ )++sseExchange :: HTTP.Manager -> HttpEndpoint -> Mux.Mux -> WireLimits -> Exchange -> IO (Either McpError Reply)+sseExchange mgr ep mux _lim ex = do+ reg <- Mux.register mux ex.requestId+ case reg of+ Left e -> pure (Left e)+ Right waiter ->+ ( do+ posted <- ssePost mgr ep ex.headers ex.body+ case posted of+ Left e -> pure (Left e)+ Right () -> Mux.await waiter+ )+ `finally` Mux.unregister mux ex.requestId
+ src/Baikai/Mcp/Transport/Stream.hs view
@@ -0,0 +1,175 @@+-- | MCP over a caller-owned byte stream: the stdio binding without the+-- process.+--+-- Each message is one line of compact UTF-8 JSON. The caller starts the+-- server, hands over its output (to read) and input (to write), and keeps+-- ownership of the process: this module launches, restarts and kills+-- nothing. One reader thread routes replies by request identifier and+-- subscription notifications by @io.modelcontextprotocol/subscriptionId@.+-- Writers are serialized so lines never interleave.+--+-- There is no per-request stream to close, so cancelling a request (or a+-- timeout) sends @notifications/cancelled@, and a late reply is dropped.+-- An end of input fails every request still waiting; a tool call among+-- them has an uncertain outcome.+module Baikai.Mcp.Transport.Stream+ ( McpStream (..),+ handleStream,+ streamBinding,+ )+where++import Baikai.Mcp.Error+import Baikai.Mcp.Internal.Binding+import Baikai.Mcp.Internal.Http (rethrowAsync)+import Baikai.Mcp.Internal.Mux qualified as Mux+import Baikai.Mcp.Protocol+import Control.Concurrent.Async (async, cancel)+import Control.Concurrent.MVar+import Control.Concurrent.STM+import Control.Exception (SomeException, mask, onException, try)+import Data.Aeson (toJSON)+import Data.Aeson qualified as Aeson+import Data.Aeson.KeyMap qualified as KeyMap+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Char8 qualified as BS8+import Data.IORef+import Data.Text (Text)+import System.IO (Handle, hClose, hFlush)++-- | The two halves of a connection to a server, supplied by the caller.+data McpStream = McpStream+ { -- | Read the next chunk from the server; empty at end of input.+ readChunk :: IO ByteString,+ -- | Write bytes to the server.+ writeChunk :: ByteString -> IO (),+ -- | Run when the connection is released, for example closing the+ -- server's input so that it exits. The process stays the caller's.+ closeStream :: Maybe (IO ())+ }++-- | A stream over the server's output (read) and input (write) handles.+-- Releasing the connection closes the input handle.+handleStream :: Handle -> Handle -> McpStream+handleStream fromServer toServer =+ McpStream+ { readChunk = BS.hGetSome fromServer 65536,+ writeChunk = \b -> BS.hPut toServer b >> hFlush toServer,+ closeStream = Just (hClose toServer)+ }++-- | A multiplexed binding over the stream. The reader starts at once.+streamBinding :: Text -> WireLimits -> McpStream -> IO Binding+streamBinding label lim s = do+ writeLock <- newMVar ()+ handlerRef <- newIORef (\_ _ _ -> pure ())+ mux <- Mux.newMux (\rid m p -> readIORef handlerRef >>= \h -> h rid m p)+ released <- newIORef False+ let writeLine :: ByteString -> IO (Either McpError ())+ writeLine bytes+ | BS8.elem '\n' bytes = pure (Left (mcpError InvalidInput NotSent "an encoded message contains a newline"))+ | otherwise = do+ failed <- Mux.failure mux+ case failed of+ Just e -> pure (Left e {delivery = NotSent})+ Nothing -> do+ r <- try @SomeException (withMVar writeLock (\_ -> s.writeChunk (bytes <> "\n")))+ case r of+ Left e -> rethrowAsync e >> pure (Left (mcpError TransportFailure Uncertain "writing to the server failed"))+ Right () -> pure (Right ())+ cancelRequest rid = do+ _ <- try @SomeException (writeLine (BS.toStrict (Aeson.encode (encodeNotification "notifications/cancelled" (KeyMap.fromList [("requestId", toJSON rid)])))))+ pure ()+ reader <- async (readLoop lim s mux)+ let release = do+ was <- atomicModifyIORef' released (True,)+ if was+ then pure ()+ else do+ cancel reader+ Mux.failAll mux (mcpError ConnectionReleased NotSent "the MCP connection has been released")+ maybe (pure ()) (\c -> () <$ try @SomeException c) s.closeStream+ exchange _ ex = do+ reg <- Mux.register mux ex.requestId+ case reg of+ Left e -> pure (Left e)+ Right waiter -> mask $ \restore -> do+ written <- restore (writeLine ex.body) `onException` Mux.unregister mux ex.requestId+ case written of+ Left e -> Mux.unregister mux ex.requestId >> pure (Left e)+ Right () -> do+ r <-+ restore (Mux.await waiter)+ `onException` (Mux.unregister mux ex.requestId >> cancelRequest ex.requestId)+ Mux.unregister mux ex.requestId+ pure r+ openStream _ ex = do+ reg <- Mux.registerListener mux ex.requestId+ case reg of+ Left e -> pure (Left e)+ Right queue -> do+ written <- writeLine ex.body+ case written of+ Left e -> Mux.unregisterListener mux ex.requestId >> pure (Left e)+ Right () -> do+ ended <- newIORef False+ let next = do+ item <- atomically (readTQueue queue)+ case item of+ StreamEnded _ -> writeIORef ended True+ StreamMessage (IncomingResponse _ _) -> writeIORef ended True+ StreamMessage (IncomingNotification "notifications/cancelled" _) -> writeIORef ended True+ _ -> pure ()+ pure item+ close = do+ Mux.unregisterListener mux ex.requestId+ done <- atomicModifyIORef' ended (True,)+ if done then pure () else cancelRequest ex.requestId+ pure (Right MessageStream {next = next, close = close})+ pure+ Binding+ { shape = ByteStream,+ endpointText = label,+ origin = label,+ exchange = exchange,+ post = \_ body -> writeLine body,+ openStream = Just openStream,+ terminate = Nothing,+ release = release,+ unsolicited = Just handlerRef+ }++-- | Split input into lines under the frame limit and route each message.+-- Any unreadable line, oversized line or end of input fails the channel.+readLoop :: WireLimits -> McpStream -> Mux.Mux -> IO ()+readLoop lim s mux = do+ r <- try @SomeException (go BS.empty)+ case r of+ Left e -> do+ rethrowAsync e+ Mux.failAll mux (mcpError TransportFailure Uncertain "reading from the server failed")+ Right () -> pure ()+ where+ go buffered = case BS8.elemIndex '\n' buffered of+ Just i+ | i > lim.maxFrameBytes ->+ Mux.failAll mux (mcpError LimitExceeded Uncertain "the server wrote a line longer than the frame limit")+ Just i -> do+ let line = BS8.takeWhile (/= '\r') (BS.take i buffered)+ rest = BS.drop (i + 1) buffered+ if BS.null (BS8.strip line)+ then go rest+ else case Aeson.eitherDecodeStrict line of+ Left _ -> Mux.failAll mux (mcpError MalformedReply Uncertain "the server wrote a line that is not JSON")+ Right v -> case decodeMessage v of+ Left why -> Mux.failAll mux (mcpError MalformedReply Uncertain ("the server wrote an invalid message: " <> why))+ Right msg -> Mux.dispatch mux (BS.length line) msg >> go rest+ Nothing+ | BS.length buffered > lim.maxFrameBytes ->+ Mux.failAll mux (mcpError LimitExceeded Uncertain "the server wrote a line longer than the frame limit")+ | otherwise -> do+ chunk <- s.readChunk+ if BS.null chunk+ then Mux.failAll mux (mcpError TransportFailure Uncertain "the server closed its output")+ else go (buffered <> chunk)
+ test/AuthSpec.hs view
@@ -0,0 +1,543 @@+module AuthSpec (tests) where++import Baikai.Mcp.Auth+import Baikai.Mcp.Client+import Baikai.Mcp.Protocol+import Baikai.Mcp.Tool+import Control.Concurrent (forkIO, threadDelay)+import Control.Concurrent.Async (concurrently)+import Control.Concurrent.MVar+import Control.Exception (SomeException, try)+import Control.Monad (void)+import Data.Aeson (Value (..), object, (.=))+import Data.Aeson.KeyMap qualified as KeyMap+import Data.ByteString (ByteString)+import Data.ByteString.Char8 qualified as BS8+import Data.ByteString.Lazy qualified as LBS+import Data.IORef+import Data.List (isInfixOf)+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.Encoding qualified as TE+import McpStub+import Network.HTTP.Client qualified as HTTP+import Network.HTTP.Client.TLS qualified as TLS+import Network.HTTP.Types (parseQueryText)+import Network.Socket qualified as Net+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (Assertion, assertBool, assertFailure, testCase, (@?=))++tests :: TestTree+tests =+ testGroup+ "Authentication"+ [ static,+ oauth,+ loopback+ ]++-- | Every secret in these tests contains SENTINEL, so a leak is easy to+-- spot in any rendered value.+noLeak :: String -> Assertion+noLeak shown = assertBool ("a secret was rendered: " <> take 300 shown) (not ("SENTINEL" `isInfixOf` shown))++-- ---------------------------------------------------------------------------+-- Static credentials++resolverFrom :: IORef (Map.Map Text ByteString) -> CredentialResolver+resolverFrom ref = CredentialResolver $ \r -> do+ m <- readIORef ref+ pure (maybe (Left "unknown reference") (Right . secret) (Map.lookup r.refName m))++protectedStatic :: IORef ByteString -> ModernHandler -> Stub -> StubRequest -> IO StubReply+protectedStatic expected inner stub r = do+ want <- readIORef expected+ if header "Authorization" r == Just ("Bearer " <> want) && header "X-Api-Key" r == Just "key-SENTINEL"+ then modernServer inner stub r+ else pure (ReplyRaw 401 [("WWW-Authenticate", "Bearer realm=\"stub\"")] "")++static :: TestTree+static =+ testGroup+ "static credentials"+ [ testCase "anonymous access is refused; scoped references are accepted and rotate" $ do+ expected <- newIORef "bearer-SENTINEL-1"+ values <- newIORef (Map.fromList [("api-bearer", "bearer-SENTINEL-1"), ("api-key", "key-SENTINEL")])+ withStub (protectedStatic expected (\_ r _ _ -> pure (discover r))) $ \stub -> do+ anon <- connectMcp (config stub) >>= expectErr+ anon.httpStatus @?= Just 401+ hook <-+ either (\e -> assertFailure (show e) >> error "unreachable") pure $+ staticCredentialHook stub.url (resolverFrom values) StaticCredentials {bearer = Just (CredentialRef "api-bearer"), headers = [("X-Api-Key", CredentialRef "api-key")]}+ c <- connectOrFail (config stub) {requestHook = hook}+ writeIORef expected "bearer-SENTINEL-2"+ modifyIORef' values (Map.insert "api-bearer" "bearer-SENTINEL-2")+ r <- callMethod c (mcpCall "server/discover" KeyMap.empty)+ assertBool "rotated credential accepted" (either (const False) (const True) r)+ closeMcp c+ noLeak (show anon),+ testCase "credentials are never released to another origin" $ do+ values <- newIORef (Map.fromList [("t", "tok-SENTINEL")])+ hook <-+ either (\e -> assertFailure (show e) >> error "unreachable") pure $+ staticCredentialHook "https://mcp.example.com/mcp" (resolverFrom values) StaticCredentials {bearer = Just (CredentialRef "t"), headers = []}+ d <- runRequestHook hook (attemptAt "https://evil.example.com:443")+ case d of+ SendDenied _ -> pure ()+ other -> assertFailure (show other)+ d2 <- runRequestHook hook (attemptAt "https://mcp.example.com:443")+ case d2 of+ SendAllowed [h] -> do+ sendHeaderName h @?= "Authorization"+ noLeak (show h)+ other -> assertFailure (show other),+ testCase "invalid, reserved and duplicate header names are configuration errors" $ do+ let mk hs = staticCredentialHook "https://mcp.example.com/mcp" (CredentialResolver (\_ -> pure (Left "x"))) StaticCredentials {bearer = Nothing, headers = hs}+ mapM_+ (\hs -> assertBool (show (map fst hs)) (either (const True) (const False) (mk hs)))+ [ [("Authorization", CredentialRef "a")],+ [("Mcp-Method", CredentialRef "a")],+ [("Bad Header", CredentialRef "a")],+ [("X-Key", CredentialRef "a"), ("x-key", CredentialRef "b")]+ ]+ assertBool "embedded credentials in the endpoint" . either (const True) (const False) $+ staticCredentialHook "https://u:p@mcp.example.com/mcp" (CredentialResolver (\_ -> pure (Left "x"))) noStaticCredentials,+ testCase "a value with a line break is refused" $ do+ values <- newIORef (Map.fromList [("t", "tok-SENTINEL\r\nX-Injected: 1")])+ hook <-+ either (\e -> assertFailure (show e) >> error "unreachable") pure $+ staticCredentialHook "https://mcp.example.com/mcp" (resolverFrom values) StaticCredentials {bearer = Just (CredentialRef "t"), headers = []}+ d <- runRequestHook hook (attemptAt "https://mcp.example.com:443")+ case d of+ SendDenied why -> noLeak (show why)+ other -> assertFailure (show other),+ testCase "cancellation before the first send transmits nothing" $ do+ gate <- newEmptyMVar+ withStub (modernServer (\_ r _ _ -> pure (discover r))) $ \stub -> do+ let blocking = CredentialResolver (\_ -> takeMVar gate >> pure (Right (secret "late-SENTINEL")))+ hook <-+ either (\e -> assertFailure (show e) >> error "unreachable") pure $+ staticCredentialHook stub.url blocking StaticCredentials {bearer = Just (CredentialRef "t"), headers = []}+ r <- timeout 200000 (connectMcp (config stub) {requestHook = hook})+ case r of+ Nothing -> pure ()+ Just _ -> assertFailure "expected the connect to be cancelled"+ length <$> stub.requests >>= (@?= 0)+ ]++attemptAt :: Text -> SendAttempt+attemptAt o =+ SendAttempt+ { serverName = "s",+ endpoint = o,+ origin = o,+ method = "server/discover",+ target = Nothing,+ cursor = Nothing,+ purpose = PurposeDiscovery+ }++-- ---------------------------------------------------------------------------+-- OAuth fixture++data AsVariant = AsVariant+ { issuerOverride :: Maybe Text,+ pkce :: Bool,+ issSupported :: Bool,+ cimd :: Bool,+ registration :: Bool,+ expiresIn :: Int,+ prmResourceOverride :: Maybe Text+ }++baseVariant :: AsVariant+baseVariant = AsVariant Nothing True True False False 3600 Nothing++data AsState = AsState+ { codes :: IORef (Map.Map Text (Text, Text, Text, Text)),+ validAccess :: IORef [ByteString],+ validRefresh :: IORef [Text],+ tokenRequests :: IORef [[(Text, Text)]],+ registrations :: IORef [Value],+ serial :: IORef Int,+ mcpResource :: IORef Text+ }++newAsState :: IO AsState+newAsState = AsState <$> newIORef Map.empty <*> newIORef [] <*> newIORef [] <*> newIORef [] <*> newIORef [] <*> newIORef 0 <*> newIORef ""++baseOf :: Stub -> Text+baseOf stub = fromMaybe stub.url (Text.stripSuffix "/mcp" stub.url)++formOf :: StubRequest -> [(Text, Text)]+formOf r = [(k, fromMaybe "" v) | (k, v) <- parseQueryText (LBS.toStrict r.body)]++asServer :: AsVariant -> AsState -> Stub -> StubRequest -> IO StubReply+asServer v st stub r = case (r.httpMethod, r.path) of+ ("GET", "/.well-known/oauth-authorization-server") ->+ pure . ok . object $+ [ "issuer" .= fromMaybe (baseOf stub) v.issuerOverride,+ "authorization_endpoint" .= (baseOf stub <> "/authorize"),+ "token_endpoint" .= (baseOf stub <> "/token"),+ "authorization_response_iss_parameter_supported" .= v.issSupported,+ "client_id_metadata_document_supported" .= v.cimd+ ]+ <> ["code_challenge_methods_supported" .= ["S256" :: Text] | v.pkce]+ <> ["registration_endpoint" .= (baseOf stub <> "/register") | v.registration]+ ("POST", "/register") -> do+ modifyIORef' st.registrations (<> [fromMaybe Null r.json])+ pure (ReplyJson 201 [] (object ["client_id" .= ("dyn-client" :: Text)]))+ ("POST", "/token") -> do+ let form = formOf r+ get k = lookup k form+ modifyIORef' st.tokenRequests (<> [form])+ expectedResource <- readIORef st.mcpResource+ case get "grant_type" of+ Just "authorization_code" -> do+ cs <- readIORef st.codes+ case get "code" >>= (`Map.lookup` cs) of+ Just (challenge, redirect, resource, client)+ | Just (pkceChallenge (fromMaybe "" (get "code_verifier"))) == Just challenge,+ get "redirect_uri" == Just redirect,+ get "resource" == Just resource,+ resource == expectedResource,+ get "client_id" == Just client -> do+ modifyIORef' st.codes (Map.delete (fromMaybe "" (get "code")))+ issue v.expiresIn+ _ -> pure (ReplyJson 400 [] (object ["error" .= ("invalid_grant" :: Text)]))+ Just "refresh_token" -> do+ valid <- readIORef st.validRefresh+ case get "refresh_token" of+ Just rt+ | rt `elem` valid,+ get "resource" == Just expectedResource -> do+ modifyIORef' st.validRefresh (filter (/= rt))+ issue 3600+ _ -> pure (ReplyJson 400 [] (object ["error" .= ("invalid_grant" :: Text)]))+ _ -> pure (ReplyJson 400 [] (object ["error" .= ("unsupported_grant_type" :: Text)]))+ _ -> pure (ReplyRaw 404 [] "")+ where+ issue lifetime = do+ n <- atomicModifyIORef' st.serial (\x -> (x + 1, x + 1))+ let at = "AT-SENTINEL-" <> Text.pack (show n)+ rt = "RT-SENTINEL-" <> Text.pack (show n)+ modifyIORef' st.validAccess (<> [TE.encodeUtf8 at])+ modifyIORef' st.validRefresh (<> [rt])+ pure (ok (object ["access_token" .= at, "token_type" .= ("Bearer" :: Text), "expires_in" .= (lifetime :: Int), "refresh_token" .= rt, "scope" .= ("files:read" :: Text)]))++-- | A protected modern MCP server. Its tools/call for "write_file" needs a+-- scope the grant lacks.+mcpServer :: AsVariant -> Stub -> AsState -> Stub -> StubRequest -> IO StubReply+mcpServer v as st stub r+ | r.httpMethod == "GET" && r.path == "/.well-known/oauth-protected-resource/mcp" =+ pure . ok $ object ["resource" .= fromMaybe stub.url v.prmResourceOverride, "authorization_servers" .= [baseOf as], "scopes_supported" .= ["files:read" :: Text]]+ | otherwise = do+ valid <- readIORef st.validAccess+ case header "Authorization" r >>= BS8.stripPrefix "Bearer " of+ Just tok | tok `elem` valid -> modernServer inner stub r+ _ -> pure (ReplyRaw 401 [("WWW-Authenticate", TE.encodeUtf8 ("Bearer resource_metadata=\"" <> baseOf stub <> "/.well-known/oauth-protected-resource/mcp\", scope=\"files:read\""))] "")+ where+ inner _ req m p = pure $ case m of+ "server/discover" -> discover req+ "tools/list" -> okResult req ["tools" .= [object ["name" .= ("write_file" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text)]]]]+ "tools/call" | KeyMap.lookup "name" p == Just "write_file" -> ReplyRaw 403 [("WWW-Authenticate", "Bearer error=\"insufficient_scope\", scope=\"files:write\"")] ""+ "tools/call" | KeyMap.lookup "name" p == Just "ghost" -> ReplySse 200 [] [Chunk ":\n\n"]+ _ -> rpcErrorReply 404 req (-32601) "no" Nothing++-- | Acts as the browser and the authorization server's consent page.+data Consent = Consent {issParam :: Maybe (Maybe Text), stateOverride :: Maybe Text, errorParam :: Maybe Text}++consent :: Consent+consent = Consent Nothing Nothing Nothing++scriptedAuthorizer :: AsState -> Stub -> Consent -> IORef [(Text, Text)] -> InteractiveAuthorizer+scriptedAuthorizer st as c seen = InteractiveAuthorizer $ \req -> do+ let query = snd (Text.breakOn "?" req.authorizationUrl)+ params = [(k, fromMaybe "" val) | (k, val) <- parseQueryText (TE.encodeUtf8 (Text.drop 1 query))]+ get k = fromMaybe "" (lookup k params)+ writeIORef seen params+ n <- atomicModifyIORef' st.serial (\x -> (x + 1, x + 1))+ let code = "CODE-SENTINEL-" <> Text.pack (show n)+ modifyIORef' st.codes (Map.insert code (get "code_challenge", get "redirect_uri", get "resource", get "client_id"))+ let iss = fromMaybe (Just (baseOf as)) c.issParam+ pure . Right . AuthorizationCallback $+ maybe [("code", code)] (\e -> [("error", e), ("error_description", "SENTINEL description")]) c.errorParam+ <> [("state", fromMaybe (get "state") c.stateOverride)]+ <> maybe [] (\i -> [("iss", i)]) iss++data Env = Env {as :: Stub, mcp :: Stub, st :: AsState, mgr :: HTTP.Manager}++withOAuth :: AsVariant -> (Env -> IO a) -> IO a+withOAuth v k = do+ st <- newAsState+ mgr <- TLS.newTlsManager+ withStub (asServer v st) $ \asStub ->+ withStub (mcpServer v asStub st) $ \mcpStub -> do+ writeIORef st.mcpResource mcpStub.url+ k Env {as = asStub, mcp = mcpStub, st = st, mgr = mgr}++providerFor :: Env -> (OAuthConfig -> OAuthConfig) -> IO (OAuthProvider, TokenStore)+providerFor env f = do+ store <- newInMemoryTokenStore+ let cfg = (oauthConfig env.mcp.url "alice" "http://127.0.0.1:53682/callback") {preRegistered = [ClientRegistration "pre-client" Nothing (baseOf env.as)]}+ r <- newOAuthProvider env.mgr store (f cfg)+ case r of+ Right p -> pure (p, store)+ Left e -> assertFailure (show e) >> error "unreachable"++challengeOf :: Env -> IO (Maybe Text)+challengeOf env = do+ e <- connectMcp (config env.mcp) >>= expectErr+ e.httpStatus @?= Just 401+ pure e.challenge++tokenCount :: Env -> IO Int+tokenCount env = length <$> readIORef env.st.tokenRequests++oauth :: TestTree+oauth =+ testGroup+ "delegated OAuth"+ [ testCase "challenge, discovery, consent and token exchange reach the protected resource" $+ withOAuth baseVariant $ \env -> do+ seen <- newIORef []+ (p, store) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})+ ch <- challengeOf env+ r <- authorizeFromChallenge p ch []+ r @?= Right Authorized+ params <- readIORef seen+ lookup "response_type" params @?= Just "code"+ lookup "code_challenge_method" params @?= Just "S256"+ lookup "resource" params @?= Just env.mcp.url+ lookup "scope" params @?= Just "files:read"+ lookup "client_id" params @?= Just "pre-client"+ [form] <- readIORef env.st.tokenRequests+ lookup "resource" form @?= Just env.mcp.url+ lookup "redirect_uri" form @?= lookup "redirect_uri" params+ c <- connectOrFail (config env.mcp) {requestHook = oauthRequestHook p}+ closeMcp c+ g <- store.loadGrant "alice" env.mcp.url+ fmap (.issuer) g @?= Just (baseOf env.as)+ noLeak (show g),+ testCase "a redirect from another issuer is never redeemed" $+ withOAuth baseVariant $ \env -> do+ seen <- newIORef []+ (p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent {issParam = Just (Just "https://evil.example")} seen)})+ ch <- challengeOf env+ authorizeFromChallenge p ch [] >>= (@?= Left AuthCallbackIssuerMismatch)+ tokenCount env >>= (@?= 0),+ testCase "a missing iss is rejected when the server advertises it" $+ withOAuth baseVariant $ \env -> do+ seen <- newIORef []+ (p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent {issParam = Just Nothing} seen)})+ ch <- challengeOf env+ authorizeFromChallenge p ch [] >>= (@?= Left AuthCallbackIssuerMismatch)+ tokenCount env >>= (@?= 0),+ testCase "a missing iss is accepted when the server does not advertise it" $+ withOAuth baseVariant {issSupported = False} $ \env -> do+ seen <- newIORef []+ (p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent {issParam = Just Nothing} seen)})+ ch <- challengeOf env+ authorizeFromChallenge p ch [] >>= (@?= Right Authorized),+ testCase "an error response from the wrong issuer is not acted on" $+ withOAuth baseVariant $ \env -> do+ seen <- newIORef []+ (p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent {issParam = Just (Just "https://evil.example"), errorParam = Just "access_denied"} seen)})+ ch <- challengeOf env+ r <- authorizeFromChallenge p ch []+ r @?= Left AuthCallbackIssuerMismatch+ noLeak (show r),+ testCase "a wrong state is rejected before redemption" $+ withOAuth baseVariant $ \env -> do+ seen <- newIORef []+ (p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent {stateOverride = Just "forged"} seen)})+ ch <- challengeOf env+ authorizeFromChallenge p ch [] >>= (@?= Left AuthStateMismatch)+ tokenCount env >>= (@?= 0),+ testCase "metadata naming a different issuer is not used" $+ withOAuth baseVariant {issuerOverride = Just "https://honest.example"} $ \env -> do+ (p, _) <- providerFor env id+ ch <- challengeOf env+ r <- authorizeFromChallenge p ch []+ case r of+ Left (AuthIssuerMismatch _) -> pure ()+ other -> assertFailure (show other),+ testCase "resource metadata for another resource is refused" $+ withOAuth baseVariant {prmResourceOverride = Just "https://other.example/mcp"} $ \env -> do+ (p, _) <- providerFor env id+ ch <- challengeOf env+ r <- authorizeFromChallenge p ch []+ case r of+ Left (AuthWrongResource _) -> pure ()+ other -> assertFailure (show other),+ testCase "an authorization server without PKCE S256 is refused" $+ withOAuth baseVariant {pkce = False} $ \env -> do+ (p, _) <- providerFor env id+ ch <- challengeOf env+ authorizeFromChallenge p ch [] >>= (@?= Left AuthPkceUnsupported),+ testCase "an unattended host gets an interaction-required outcome" $+ withOAuth baseVariant $ \env -> do+ (p, _) <- providerFor env id+ ch <- challengeOf env+ r <- authorizeFromChallenge p ch []+ case r of+ Right (InteractionRequired req) -> do+ req.issuer @?= baseOf env.as+ assertBool "authorization URL" ("/authorize?" `Text.isInfixOf` req.authorizationUrl)+ other -> assertFailure (show other)+ tokenCount env >>= (@?= 0),+ testCase "the well-known fallback finds metadata without a challenge" $+ withOAuth baseVariant $ \env -> do+ seen <- newIORef []+ (p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})+ authorizeFromChallenge p Nothing [] >>= (@?= Right Authorized),+ testCase "two parallel requests with an expired token cause one rotation" $+ withOAuth baseVariant {expiresIn = 1} $ \env -> do+ seen <- newIORef []+ (p, store) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})+ ch <- challengeOf env+ authorizeFromChallenge p ch [] >>= (@?= Right Authorized)+ let cfg = (config env.mcp) {requestHook = oauthRequestHook p}+ (a, b) <- concurrently (connectMcp cfg) (connectMcp cfg)+ assertBool "both connected" (either (const False) (const True) a && either (const False) (const True) b)+ forms <- readIORef env.st.tokenRequests+ length [f | f <- forms, lookup "grant_type" f == Just "refresh_token"] @?= 1+ g <- store.loadGrant "alice" env.mcp.url+ fmap (fmap revealSecret . (.tokens.refreshToken)) g @?= Just (Just "RT-SENTINEL-3")+ mapM_ (either (const (pure ())) closeMcp) [a, b],+ testCase "a revoked grant asks for a fresh authorization" $+ withOAuth baseVariant {expiresIn = 1} $ \env -> do+ seen <- newIORef []+ (p, store) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})+ ch <- challengeOf env+ authorizeFromChallenge p ch [] >>= (@?= Right Authorized)+ writeIORef env.st.validRefresh []+ e <- connectMcp (config env.mcp) {requestHook = oauthRequestHook p} >>= expectErr+ e.httpStatus @?= Just 401+ store.loadGrant "alice" env.mcp.url >>= (@?= Nothing)+ r <- recoverFromChallenge p e+ case r of+ Right (AccessDenied _) -> pure ()+ other -> assertFailure (show other),+ testCase "a 401 with a refreshable grant recovers by refreshing once" $+ withOAuth baseVariant $ \env -> do+ seen <- newIORef []+ (p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})+ ch <- challengeOf env+ authorizeFromChallenge p ch [] >>= (@?= Right Authorized)+ writeIORef env.st.validAccess []+ e <- connectMcp (config env.mcp) {requestHook = oauthRequestHook p} >>= expectErr+ recoverFromChallenge p e >>= (@?= Right Authorized)+ c <- connectOrFail (config env.mcp) {requestHook = oauthRequestHook p}+ closeMcp c,+ testCase "insufficient scope is reported, not silently widened; other 403s stay denied" $+ withOAuth baseVariant $ \env -> do+ seen <- newIORef []+ (p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})+ ch <- challengeOf env+ authorizeFromChallenge p ch [] >>= (@?= Right Authorized)+ c <- connectOrFail (config env.mcp) {requestHook = oauthRequestHook p}+ listing <- listTools c defaultDrainLimits+ writer <- case listing of+ Right ToolListing {tools = [t]} -> pure t+ other -> assertFailure (show other) >> error "unreachable"+ before <- tokenCount env+ r <- callTool c (mcpToolCall writer KeyMap.empty)+ case r of+ Left (ToolRequestFailed e) -> do+ recoverFromChallenge p e >>= (@?= Right (InsufficientScope ["files:write"]))+ recoverFromChallenge p e {challenge = Nothing} >>= \case+ Right (AccessDenied _) -> pure ()+ other -> assertFailure (show other)+ other -> assertFailure (show other)+ tokenCount env >>= (@?= before)+ closeMcp c,+ testCase "a host policy still denies the repeated page of an authenticated client" $+ withOAuth baseVariant $ \env -> do+ seen <- newIORef []+ (p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})+ ch <- challengeOf env+ authorizeFromChallenge p ch [] >>= (@?= Right Authorized)+ let policy = McpRequestHook (\att -> pure (if att.method == "tools/list" then SendDenied "not in this run" else SendAllowed []))+ c <- connectOrFail (config env.mcp) {requestHook = policy <> oauthRequestHook p}+ r <- listToolsPage c Nothing+ either (\e -> e.kind @?= RequestDenied) (const (assertFailure "expected a denial")) r+ length . filter ((== Just "tools/list") . rpcMethod) <$> env.mcp.requests >>= (@?= 0)+ closeMcp c,+ testCase "registration: dynamic registration declares a native application; a metadata document needs none" $ do+ withOAuth baseVariant {registration = True} $ \env -> do+ seen <- newIORef []+ (p, store) <- providerFor env (\c -> c {preRegistered = [], allowDynamicRegistration = True, authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})+ ch <- challengeOf env+ authorizeFromChallenge p ch [] >>= (@?= Right Authorized)+ regs <- readIORef env.st.registrations+ map (\case Object o -> KeyMap.lookup "application_type" o; _ -> Nothing) regs @?= [Just "native"]+ store.loadRegistration (baseOf env.as) >>= (@?= Just (ClientRegistration "dyn-client" Nothing (baseOf env.as)))+ withOAuth baseVariant {registration = True, cimd = True} $ \env -> do+ seen <- newIORef []+ (p, _) <- providerFor env (\c -> c {preRegistered = [], clientMetadataDocument = Just "https://client.example/meta.json", allowDynamicRegistration = True, authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})+ ch <- challengeOf env+ authorizeFromChallenge p ch [] >>= (@?= Right Authorized)+ readIORef env.st.registrations >>= (@?= [])+ lookup "client_id" <$> readIORef seen >>= (@?= Just "https://client.example/meta.json")+ withOAuth baseVariant $ \env -> do+ (p, _) <- providerFor env (\c -> c {preRegistered = []})+ ch <- challengeOf env+ r <- authorizeFromChallenge p ch []+ case r of+ Left (AuthNoRegistration _) -> pure ()+ other -> assertFailure (show other),+ testCase "a broken tool response after authentication is one invocation" $+ withOAuth baseVariant $ \env -> do+ seen <- newIORef []+ (p, _) <- providerFor env (\c -> c {authorizer = Just (scriptedAuthorizer env.st env.as consent seen)})+ ch <- challengeOf env+ authorizeFromChallenge p ch [] >>= (@?= Right Authorized)+ c <- connectOrFail (config env.mcp) {requestHook = oauthRequestHook p}+ let t = either (error . show) id (decodeTool True (object ["name" .= ("ghost" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text)]]))+ r <- callTool c (mcpToolCall t KeyMap.empty)+ case r of+ Left (ToolRequestFailed e) -> noLeak (show e)+ other -> assertFailure (show other)+ length . filter ((== Just "tools/call") . rpcMethod) <$> env.mcp.requests >>= (@?= 1)+ closeMcp c+ ]++-- ---------------------------------------------------------------------------+-- Loopback++freePort :: IO Int+freePort = do+ sock <- Net.socket Net.AF_INET Net.Stream Net.defaultProtocol+ Net.bind sock (Net.SockAddrInet 0 (Net.tupleToHostAddress (127, 0, 0, 1)))+ port <- Net.socketPort sock+ Net.close sock+ pure (fromIntegral port)++loopback :: TestTree+loopback =+ testGroup+ "loopback authorizer"+ [ testCase "captures one redirect and releases the port" $ do+ port <- freePort+ mgr <- TLS.newTlsManager+ let browse _ = void . forkIO $ do+ threadDelay 50000+ req <- HTTP.parseRequest ("http://127.0.0.1:" <> show port <> "/callback?code=CODE-SENTINEL&state=s1&iss=https%3A%2F%2Fas.example")+ void (try @SomeException (HTTP.httpLbs req mgr))+ authz = loopbackAuthorizer LoopbackConfig {port = port, callbackPath = "/callback", present = browse, waitFor = 5}+ r <- runAuthorization authz (AuthorizationRequest "https://as.example/authorize" ("http://127.0.0.1:" <> Text.pack (show port) <> "/callback") "https://as.example" [])+ case r of+ Right (AuthorizationCallback ps) -> do+ lookup "state" ps @?= Just "s1"+ lookup "iss" ps @?= Just "https://as.example"+ noLeak (show (AuthorizationCallback ps))+ Left e -> assertFailure (show e)+ again <- runAuthorization (loopbackAuthorizer LoopbackConfig {port = port, callbackPath = "/callback", present = const (pure ()), waitFor = 0.2}) (AuthorizationRequest "u" "r" "i" [])+ case again of+ Left _ -> pure ()+ Right _ -> assertFailure "expected the wait to expire"+ ]
+ test/ClientSpec.hs view
@@ -0,0 +1,189 @@+-- | A consumer that uses only the public API.+module ClientSpec (tests) where++import Baikai.Mcp.Client+import Baikai.Mcp.Protocol+import Control.Exception (SomeException, try)+import Data.Aeson (Key, Value (..), object, (.=))+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Parser, parseJSON)+import Data.Text (Text)+import McpStub+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++tests :: TestTree+tests =+ testGroup+ "Public client"+ [ pages,+ subscriptions,+ lifecycle+ ]++-- | Two pages of tool names; the second page's cursor is opaque.+pagedServer :: ModernHandler+pagedServer _ r m p = pure $ case m of+ "server/discover" -> discover r+ "tools/list" -> case KeyMap.lookup "cursor" p of+ Nothing -> okResult r (page ["a", "b"] (Just "opaque==") 1000)+ Just "opaque==" -> okResult r (page ["c"] Nothing 500)+ Just _ -> rpcErrorReply 400 r (-32602) "invalid cursor" Nothing+ _ -> rpcErrorReply 404 r (-32601) "no" Nothing+ where+ page :: [Text] -> Maybe Text -> Int -> [(Key, Value)]+ page names next ttl =+ ["resultType" .= ("complete" :: Text), "tools" .= map (\n -> object ["name" .= n]) names, "ttlMs" .= ttl, "cacheScope" .= ("private" :: Text)]+ <> maybe [] (\c -> ["nextCursor" .= c]) next++toolName :: Value -> Parser Text+toolName = \case+ Object o | Just (String n) <- KeyMap.lookup "name" o -> pure n+ v -> parseJSON v++pages :: TestTree+pages =+ testGroup+ "pages"+ [ testCase "one page, then the next is denied before transmission" $+ withStub (modernServer pagedServer) $ \stub -> do+ let hook = McpRequestHook $ \att -> pure (maybe (SendAllowed []) (const (SendDenied "one page only")) att.cursor)+ c <- connectOrFail (config stub) {requestHook = hook}+ p1 <- requestPage c "tools/list" "tools" toolName Nothing+ case p1 of+ Right p -> do+ p.items @?= ["a", "b"]+ fmap cursorToText p.nextCursor @?= Just "opaque=="+ p.cache @?= Just (CacheHint 1000 CachePrivate)+ e <- requestPage c "tools/list" "tools" toolName p.nextCursor >>= expectErr+ e.kind @?= RequestDenied+ Left e -> assertFailure (show e)+ methodsOf <$> stub.requests >>= (@?= ["server/discover", "tools/list"]),+ testCase "a bounded drain follows the opaque cursor" $+ withStub (modernServer pagedServer) $ \stub -> do+ c <- connectOrFail (config stub)+ r <- drainPages defaultDrainLimits (requestPage c "tools/list" "tools" toolName)+ either (assertFailure . show) (@?= ["a", "b", "c"]) r+ map (KeyMap.lookup "cursor" . rpcParams) . filter ((== Just "tools/list") . rpcMethod) <$> stub.requests+ >>= (@?= [Nothing, Just "opaque=="])+ ]++data Ending = HoldIt | Graceful | ServerCancel | DropIt++listenServer :: Ending -> ModernHandler+listenServer ending _ r m _ = pure $ case m of+ "server/discover" -> discover r+ "tools/list" -> okResult r ["tools" .= ([] :: [Value])]+ "subscriptions/listen" ->+ let sid = rpcId r+ note method extra = sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "method" .= (method :: Text), "params" .= object (("_meta" .= object ["io.modelcontextprotocol/subscriptionId" .= sid]) : extra)])+ foreign' = sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "method" .= ("notifications/tools/list_changed" :: Text), "params" .= object ["_meta" .= object ["io.modelcontextprotocol/subscriptionId" .= (987654 :: Int)]]])+ ack = note "notifications/subscriptions/acknowledged" ["notifications" .= object ["toolsListChanged" .= True]]+ end = case ending of+ HoldIt -> [HoldOpen]+ Graceful -> [Chunk (sseResult r ["resultType" .= ("complete" :: Text), "_meta" .= object ["io.modelcontextprotocol/subscriptionId" .= sid]])]+ ServerCancel -> [Chunk (sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "method" .= ("notifications/cancelled" :: Text), "params" .= object ["requestId" .= sid]]))]+ DropIt -> []+ in ReplySse 200 [] ([Chunk ack, Chunk (note "notifications/prompts/list_changed" []), Chunk foreign', Chunk ":\n\n", Chunk (note "notifications/tools/list_changed" [])] <> end)+ _ -> rpcErrorReply 404 r (-32601) "no" Nothing++requestedFilter :: SubscriptionFilter+requestedFilter = emptySubscriptionFilter {toolsListChanged = True, promptsListChanged = True}++subscriptions :: TestTree+subscriptions =+ testGroup+ "subscriptions"+ [ testCase "acknowledged subset, filtering, and release independent of ordinary calls" $+ withStub (modernServer (listenServer HoldIt)) $ \stub -> do+ c <- connectOrFail (config stub)+ r <- withSubscription c requestedFilter $ \sub -> do+ subscriptionAcknowledged sub @?= emptySubscriptionFilter {toolsListChanged = True}+ subscriptionRequested sub @?= requestedFilter+ connectionOpenListeners c >>= (@?= 1)+ ev <- nextSubscriptionEvent sub+ case ev of+ SubscriptionNotification m _ -> m @?= "notifications/tools/list_changed"+ other -> assertFailure (show other)+ listed <- callMethod c (mcpCall "tools/list" KeyMap.empty)+ assertBool "ordinary call works while listening" (either (const False) (const True) listed)+ r @?= Right ()+ connectionOpenListeners c >>= (@?= 0)+ waitFor 50 ((>= 1) <$> stub.clientClosed)+ listed <- callMethod c (mcpCall "tools/list" KeyMap.empty)+ assertBool "ordinary call works after release" (either (const False) (const True) listed)+ closeMcp c,+ testCase "a listen response is a graceful end" $ endsWith Graceful EndedGracefully,+ testCase "notifications/cancelled from the server ends the subscription" $ endsWith ServerCancel EndedByServer,+ testCase "a stream closing without either signal is a disconnect" $ endsWith DropIt Disconnected,+ testCase "a timeout inside the subscription leaves no open listener" $+ withStub (modernServer (listenServer HoldIt)) $ \stub -> do+ c <- connectOrFail (config stub)+ r <- timeout 300000 (withSubscription c requestedFilter (\sub -> nextSubscriptionEvent sub >> nextSubscriptionEvent sub))+ case r of+ Nothing -> pure ()+ Just other -> assertFailure ("expected the timeout to fire: " <> show other)+ connectionOpenListeners c >>= (@?= 0)+ waitFor 50 ((>= 1) <$> stub.clientClosed)+ closeMcp c,+ testCase "closeMcp ends open subscriptions" $+ withStub (modernServer (listenServer HoldIt)) $ \stub -> do+ c <- connectOrFail (config stub)+ _ <- withSubscription c requestedFilter $ \sub -> do+ _ <- nextSubscriptionEvent sub+ closeMcp c+ ev <- nextSubscriptionEvent sub+ ev @?= SubscriptionEnded EndedByClient+ waitFor 50 ((>= 1) <$> stub.clientClosed)+ ]+ where+ endsWith ending expected =+ withStub (modernServer (listenServer ending)) $ \stub -> do+ c <- connectOrFail (config stub)+ r <- withSubscription c requestedFilter $ \sub -> do+ _ <- nextSubscriptionEvent sub+ e1 <- nextSubscriptionEvent sub+ e2 <- nextSubscriptionEvent sub+ pure (e1, e2)+ r @?= Right (SubscriptionEnded expected, SubscriptionEnded expected)+ closeMcp c++lifecycle :: TestTree+lifecycle =+ testGroup+ "lifecycle"+ [ testCase "a released handle refuses operations without sending" $+ withStub (modernServer pagedServer) $ \stub -> do+ c <- connectOrFail (config stub)+ closeMcp c+ closeMcp c+ e <- callMethod c (mcpCall "tools/list" KeyMap.empty) >>= expectErr+ e.kind @?= ConnectionReleased+ e.delivery @?= NotSent+ methodsOf <$> stub.requests >>= (@?= ["server/discover"]),+ testCase "hook headers reach the server; protocol headers cannot be overridden" $+ withStub (modernServer pagedServer) $ \stub -> do+ let creds = McpRequestHook (\_ -> pure (SendAllowed [sendHeader "Authorization" "Bearer sentinel-token"]))+ c <- connectOrFail (config stub) {requestHook = creds}+ _ <- callMethod c (mcpCall "tools/list" KeyMap.empty)+ map (header "Authorization") <$> stub.requests >>= (@?= replicate 2 (Just "Bearer sentinel-token"))+ let bad = McpRequestHook (\_ -> pure (SendAllowed [sendHeader "Mcp-Method" "tools/call"]))+ e <- connectMcp (config stub) {requestHook = bad} >>= expectErr+ e.kind @?= InvalidInput+ length <$> stub.requests >>= (@?= 2)+ assertBool "the header value is not shown" (show (sendHeader "Authorization" "Bearer sentinel-token") /= "" && not (contains "sentinel" (show (sendHeader "Authorization" "Bearer sentinel-token")))),+ testCase "withMcpConnection releases on exceptions" $+ withStub (modernServer (listenServer HoldIt)) $ \stub -> do+ r <- try @SomeException $ withMcpConnection (config stub) $ \c ->+ withSubscription c requestedFilter (\_ -> ioError (userError "boom"))+ assertBool "exception propagated" (either (const True) (const False) r)+ waitFor 50 ((>= 1) <$> stub.clientClosed),+ testCase "an endpoint with embedded credentials is refused" $ do+ e <- connectMcp (mcpServerConfig "x" "https://user:secret@example.com/mcp") >>= expectErr+ e.kind @?= InvalidInput+ assertBool "secret not rendered" (not (contains "secret" (show e)))+ ]+ where+ contains :: String -> String -> Bool+ contains needle hay = any (\i -> take (length needle) (drop i hay) == needle) [0 .. length hay]
+ test/JsonSchemaSpec.hs view
@@ -0,0 +1,108 @@+module JsonSchemaSpec (tests) where++import Baikai.Mcp.JsonSchema+import Data.Aeson (Value (..), object, (.=))+import Data.Aeson qualified as Aeson+import Data.Text (Text)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (Assertion, assertBool, assertFailure, testCase, (@?=))++tests :: TestTree+tests =+ testGroup+ "JSON Schema 2020-12 (bounded)"+ [ testCase "types, integers written as 1.0, and boolean schemas" $ do+ conforms (object ["type" .= ("integer" :: Text)]) (Number 1.0)+ violates (object ["type" .= ("integer" :: Text)]) (Number 1.5)+ conforms (object ["type" .= ["string", "null" :: Text]]) Null+ conforms (Bool True) (String "x")+ violates (Bool False) (String "x"),+ testCase "objects: required, properties, additionalProperties, patternProperties" $ do+ let s =+ object+ [ "type" .= ("object" :: Text),+ "properties" .= object ["name" .= object ["type" .= ("string" :: Text)]],+ "patternProperties" .= object ["^x-" .= object ["type" .= ("integer" :: Text)]],+ "additionalProperties" .= False,+ "required" .= ["name" :: Text]+ ]+ conforms s (object ["name" .= ("a" :: Text), "x-n" .= (1 :: Int)])+ violates s (object ["name" .= ("a" :: Text), "other" .= (1 :: Int)])+ violates s (object ["x-n" .= (1 :: Int)])+ violates s (object ["name" .= ("a" :: Text), "x-n" .= ("no" :: Text)]),+ testCase "local references into $defs and composition" $ do+ let s =+ object+ [ "$defs" .= object ["pos" .= object ["type" .= ("integer" :: Text), "minimum" .= (1 :: Int)]],+ "allOf" .= [object ["$ref" .= ("#/$defs/pos" :: Text)], object ["maximum" .= (10 :: Int)]],+ "not" .= object ["const" .= (5 :: Int)]+ ]+ conforms s (Number 3)+ violates s (Number 0)+ violates s (Number 11)+ violates s (Number 5),+ testCase "$ref applies alongside sibling keywords (2020-12, not draft-07)" $ do+ let s = object ["$defs" .= object ["s" .= object ["type" .= ("string" :: Text)]], "$ref" .= ("#/$defs/s" :: Text), "maxLength" .= (2 :: Int)]+ conforms s (String "ab")+ violates s (String "abc"),+ testCase "anyOf, oneOf and if/then/else" $ do+ let one = object ["oneOf" .= [object ["type" .= ("integer" :: Text)], object ["minimum" .= (2 :: Int)]]]+ conforms one (Number 1)+ violates one (Number 3)+ let cond = object ["if" .= object ["type" .= ("string" :: Text)], "then" .= object ["minLength" .= (2 :: Int)], "else" .= object ["type" .= ("null" :: Text)]]+ conforms cond (String "ab")+ violates cond (String "a")+ violates cond (Number 1)+ conforms (object ["anyOf" .= [object ["type" .= ("null" :: Text)], object ["type" .= ("array" :: Text)]]]) Null,+ testCase "arrays: prefixItems, items, contains, uniqueItems" $ do+ let s = object ["prefixItems" .= [object ["type" .= ("string" :: Text)]], "items" .= object ["type" .= ("integer" :: Text)], "contains" .= object ["const" .= (7 :: Int)], "maxContains" .= (1 :: Int)]+ conforms s (Aeson.toJSON [String "a", Number 1, Number 7])+ violates s (Aeson.toJSON [String "a", Number 1])+ violates s (Aeson.toJSON [String "a", Number 7, Number 7])+ violates s (Aeson.toJSON [Number 1, Number 7])+ violates (object ["uniqueItems" .= True]) (Aeson.toJSON [Number 1, Number 1.0]),+ testCase "numbers and strings" $ do+ conforms (object ["multipleOf" .= (0.01 :: Double)]) (Number 0.1)+ violates (object ["multipleOf" .= (0.03 :: Double)]) (Number 0.1)+ conforms (object ["maxLength" .= (2 :: Int)]) (String "世界")+ conforms (object ["pattern" .= ("^[a-z]+\\d{2}$" :: Text)]) (String "abc12")+ violates (object ["pattern" .= ("^[a-z]+\\d{2}$" :: Text)]) (String "abc123")+ conforms (object ["pattern" .= ("b.c" :: Text)]) (String "xxbac")+ violates (object ["pattern" .= ("b.c" :: Text)]) (String "b\nc")+ violates (object ["pattern" .= ("^a$" :: Text)]) (String "x\na"),+ testCase "annotations and extension keywords do not assert" $+ conforms (object ["format" .= ("email" :: Text), "x-mcp-header" .= ("H" :: Text), "description" .= ("d" :: Text)]) (String "not an email"),+ testCase "unsupported contracts are unverifiable, never satisfied" $ do+ unverifiable (object ["$ref" .= ("https://example.com/schema.json" :: Text)]) Null+ unverifiable (object ["$schema" .= ("http://json-schema.org/draft-07/schema#" :: Text)]) Null+ unverifiable (object ["unevaluatedProperties" .= False]) (object [])+ unverifiable (object ["pattern" .= ("^(?=a)" :: Text)]) (String "a")+ unverifiable (object ["pattern" .= ("(a)\\1" :: Text)]) (String "aa")+ unverifiable (object ["$ref" .= ("#anchor" :: Text)]) Null,+ testCase "a cyclic reference exhausts the budget instead of looping" $+ unverifiable (object ["$ref" .= ("#" :: Text)]) Null,+ testCase "exponential composition stops at the step budget" $ do+ let nest :: Int -> Value+ nest 0 = object ["type" .= ("string" :: Text)]+ nest n = object ["anyOf" .= [nest (n - 1), nest (n - 1), nest (n - 1)]]+ case validateJson defaultSchemaBudget {maxSteps = 5000} (nest 12) (Number 1) of+ Unverifiable _ -> pure ()+ other -> assertFailure (show other),+ testCase "violations name the instance location" $+ case validateJson defaultSchemaBudget (object ["properties" .= object ["a/b" .= object ["items" .= object ["type" .= ("string" :: Text)]]]]) (object ["a/b" .= [Number 1]]) of+ Violates [v] -> v.instancePath @?= "/a~1b/0"+ other -> assertFailure (show other)+ ]++conforms :: Value -> Value -> Assertion+conforms s v = validateJson defaultSchemaBudget s v @?= Conforms++violates :: Value -> Value -> Assertion+violates s v = case validateJson defaultSchemaBudget s v of+ Violates _ -> pure ()+ other -> assertFailure ("expected a violation, got " <> show other)++unverifiable :: Value -> Value -> Assertion+unverifiable s v = case validateJson defaultSchemaBudget s v of+ Unverifiable _ -> pure ()+ other -> assertBool ("expected unverifiable, got " <> show other) False
+ test/LegacySpec.hs view
@@ -0,0 +1,192 @@+module LegacySpec (tests) where++import Baikai.Mcp.Client+import Baikai.Mcp.Protocol+import Data.Aeson (Value (..), object, (.=))+import Data.Aeson qualified as Aeson+import Data.Aeson.KeyMap qualified as KeyMap+import Data.ByteString (ByteString)+import Data.IORef+import Data.Text (Text)+import Data.Text.Encoding qualified as TE+import McpStub+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++tests :: TestTree+tests =+ testGroup+ "Legacy profiles"+ [ streamable,+ httpSse+ ]++data LegacyCfg = LegacyCfg+ { version :: Text,+ session :: Maybe ByteString,+ expireAfter :: Maybe Int,+ pingFirst :: Bool+ }++-- | A handshake-era Streamable HTTP server. It answers 400 with an empty+-- body to anything before initialize, as such servers commonly do.+legacyServer :: LegacyCfg -> IORef Int -> Stub -> StubRequest -> IO StubReply+legacyServer cfg served _ r+ | r.httpMethod == "DELETE" = pure (ReplyRaw 200 [] "")+ | otherwise = case rpcMethod r of+ Just "initialize"+ | header "Mcp-Session-Id" r /= Nothing -> pure (ReplyRaw 400 [] "")+ | otherwise ->+ pure . ReplyJson 200 [("Mcp-Session-Id", s) | Just s <- [cfg.session]] $+ object+ [ "jsonrpc" .= ("2.0" :: Text),+ "id" .= rpcId r,+ "result"+ .= object+ [ "protocolVersion" .= cfg.version,+ "capabilities" .= object ["tools" .= object []],+ "serverInfo" .= object ["name" .= ("legacy" :: Text), "version" .= ("0.9" :: Text)]+ ]+ ]+ Just "notifications/initialized"+ | sessionOk -> pure (ReplyRaw 202 [] "")+ | otherwise -> pure (ReplyRaw 400 [] "")+ Just "tools/list"+ | not sessionOk || not versionOk -> pure (ReplyRaw 400 [] "")+ | otherwise -> do+ n <- atomicModifyIORef' served (\x -> (x + 1, x + 1))+ case cfg.expireAfter of+ Just k | n > k -> pure (ReplyRaw 404 [] "")+ _+ | cfg.pingFirst ->+ pure (ReplySse 200 [] [Chunk (sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "id" .= ("srv-1" :: Text), "method" .= ("ping" :: Text)])), Chunk (sseResult r toolsPage)])+ | otherwise -> pure (okResult r toolsPage)+ Just _ | rpcId r == Null -> pure (ReplyRaw 202 [] "")+ _ -> pure (ReplyRaw 400 [] "")+ where+ sessionOk = header "Mcp-Session-Id" r == cfg.session+ versionOk+ | cfg.version >= "2025-06-18" = fmap TE.decodeUtf8 (header "MCP-Protocol-Version" r) == Just cfg.version+ | otherwise = True+ toolsPage = ["tools" .= [object ["name" .= ("echo" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text)]]]]++listTools :: McpConnection -> IO (Either McpError CompleteResult)+listTools c = callMethod c (mcpCall "tools/list" KeyMap.empty)++streamable :: TestTree+streamable =+ testGroup+ "handshake-era Streamable HTTP"+ [ testCase "2025-11-25 with a session: fallback, handshake, session echo and teardown" $ do+ served <- newIORef 0+ withStub (legacyServer (LegacyCfg "2025-11-25" (Just "sess-42") Nothing False) served) $ \stub -> do+ c <- connectOrFail (config stub)+ connectionEra c @?= Legacy (ProtocolVersion "2025-11-25")+ (connectionDescription c).serverInfo @?= Just (implementation "legacy" "0.9")+ r <- listTools c+ assertBool "listed" (either (const False) (const True) r)+ closeMcp c+ closeMcp c+ rs <- stub.requests+ methodsOf rs @?= ["server/discover", "initialize", "notifications/initialized", "tools/list", "DELETE"]+ map (header "Mcp-Session-Id") rs @?= [Nothing, Nothing, Just "sess-42", Just "sess-42", Just "sess-42"]+ map (header "MCP-Protocol-Version") (drop 2 rs) @?= replicate 3 (Just "2025-11-25")+ let initParams = rpcParams (rs !! 1)+ KeyMap.lookup "protocolVersion" initParams @?= Just "2025-11-25"+ assertBool "no modern _meta on legacy requests" (not (KeyMap.member "_meta" (rpcParams (rs !! 3)))),+ testCase "2025-06-18 without a session: no session header and no teardown" $ do+ served <- newIORef 0+ withStub (legacyServer (LegacyCfg "2025-06-18" Nothing Nothing False) served) $ \stub -> do+ c <- connectOrFail (config stub)+ connectionEra c @?= Legacy (ProtocolVersion "2025-06-18")+ _ <- listTools c+ closeMcp c+ rs <- stub.requests+ methodsOf rs @?= ["server/discover", "initialize", "notifications/initialized", "tools/list"]+ assertBool "no session header" (all ((== Nothing) . header "Mcp-Session-Id") rs),+ testCase "an expired session is reported, marks the handle, and is not replayed" $ do+ served <- newIORef 0+ withStub (legacyServer (LegacyCfg "2025-11-25" (Just "s") (Just 1) False) served) $ \stub -> do+ c <- connectOrFail (config stub)+ _ <- listTools c+ e <- listTools c >>= expectErr+ e.kind @?= SessionExpired+ e.delivery @?= Answered+ e2 <- listTools c >>= expectErr+ e2.kind @?= SessionExpired+ e2.delivery @?= NotSent+ readIORef served >>= (@?= 2),+ testCase "a version outside the allowlist is refused" $ do+ served <- newIORef 0+ withStub (legacyServer (LegacyCfg "2023-01-01" Nothing Nothing False) served) $ \stub -> do+ e <- connectMcp (config stub) >>= expectErr+ e.kind @?= IncompatibleServer+ methodsOf <$> stub.requests >>= (@?= ["server/discover", "initialize"]),+ testCase "an explicitly legacy endpoint skips the probe" $ do+ served <- newIORef 0+ withStub (legacyServer (LegacyCfg "2025-11-25" Nothing Nothing False) served) $ \stub -> do+ c <- connectOrFail (config stub) {profile = McpLegacyStreamableHttp}+ closeMcp c+ methodsOf <$> stub.requests >>= (@?= ["initialize", "notifications/initialized"]),+ testCase "the modern-only profile refuses a legacy server" $ do+ served <- newIORef 0+ withStub (legacyServer (LegacyCfg "2025-11-25" Nothing Nothing False) served) $ \stub -> do+ e <- connectMcp (config stub) {profile = McpModernOnly} >>= expectErr+ e.kind @?= IncompatibleServer+ methodsOf <$> stub.requests >>= (@?= ["server/discover"]),+ testCase "a ping on a response stream is answered through the hook" $ do+ served <- newIORef 0+ replies <- newIORef []+ withStub (legacyServer (LegacyCfg "2025-11-25" (Just "s") Nothing True) served) $ \stub -> do+ let hook = McpRequestHook $ \att -> modifyIORef' replies (<> [att.purpose]) >> pure (SendAllowed [])+ c <- connectOrFail (config stub) {requestHook = hook}+ r <- listTools c+ assertBool "listed" (either (const False) (const True) r)+ waitFor 50 ((== 5) . length <$> stub.requests)+ rs <- stub.requests+ let answers = [x | x <- rs, rpcId x == String "srv-1"]+ map (.json) answers @?= [Just (object ["jsonrpc" .= ("2.0" :: Text), "id" .= ("srv-1" :: Text), "result" .= object []])]+ map (header "Mcp-Session-Id") answers @?= [Just "s"]+ purposes <- readIORef replies+ assertBool "reply passed the hook" (PurposeReply `elem` purposes)+ ]++-- | A 2024-11-05 HTTP+SSE server: a GET event stream whose first event+-- names the message endpoint, and a POST endpoint whose replies travel on+-- the event stream.+sseServer :: ByteString -> Stub -> StubRequest -> IO StubReply+sseServer advertised stub r+ | r.httpMethod == "GET" = pure (ReplyChannel 200 [] ["event: endpoint\ndata: " <> advertised <> "\n\n"])+ | r.path /= "/messages" = pure (ReplyRaw 404 [] "")+ | otherwise = do+ case rpcMethod r of+ Just "initialize" ->+ stub.push (sseResult r ["protocolVersion" .= ("2024-11-05" :: Text), "capabilities" .= object ["tools" .= object []], "serverInfo" .= object ["name" .= ("old" :: Text), "version" .= ("0.1" :: Text)]])+ Just "tools/list" -> stub.push (sseResult r ["tools" .= ([] :: [Value])])+ _ -> pure ()+ pure (ReplyRaw 202 [] "")++httpSse :: TestTree+httpSse =+ testGroup+ "deprecated HTTP+SSE"+ [ testCase "GET stream, endpoint event, POSTed requests and replies on the stream" $+ withStub (sseServer "/messages?sessionId=s1") $ \stub -> do+ c <- connectOrFail (config stub) {profile = McpLegacyHttpSse}+ connectionEra c @?= Legacy (ProtocolVersion "2024-11-05")+ r <- listTools c+ case r of+ Right cr -> KeyMap.lookup "tools" cr.result @?= Just (Aeson.toJSON ([] :: [Value]))+ Left e -> assertFailure (show e)+ closeMcp c+ rs <- stub.requests+ methodsOf rs @?= ["GET", "initialize", "notifications/initialized", "tools/list"]+ map (.query) (drop 1 rs) @?= replicate 3 "?sessionId=s1"+ waitFor 50 ((>= 1) <$> stub.clientClosed),+ testCase "a message endpoint on another origin is refused before any POST" $+ withStub (sseServer "http://evil.invalid/messages") $ \stub -> do+ e <- connectMcp (config stub) {profile = McpLegacyHttpSse} >>= expectErr+ e.kind @?= IncompatibleServer+ e.delivery @?= NotSent+ methodsOf <$> stub.requests >>= (@?= ["GET"])+ ]
+ test/Main.hs view
@@ -0,0 +1,28 @@+module Main (main) where++import AuthSpec qualified+import ClientSpec qualified+import JsonSchemaSpec qualified+import LegacySpec qualified+import ModernHttpSpec qualified+import ProtocolSpec qualified+import ResourcePromptSpec qualified+import StreamSpec qualified+import Test.Tasty (defaultMain, testGroup)+import ToolSpec qualified++main :: IO ()+main =+ defaultMain $+ testGroup+ "baikai-mcp"+ [ ProtocolSpec.tests,+ ModernHttpSpec.tests,+ LegacySpec.tests,+ ClientSpec.tests,+ JsonSchemaSpec.tests,+ ToolSpec.tests,+ AuthSpec.tests,+ ResourcePromptSpec.tests,+ StreamSpec.tests+ ]
+ test/McpStub.hs view
@@ -0,0 +1,305 @@+-- | A scripted, in-process MCP server for wire tests.+--+-- Each test supplies a handler from a captured request to a reply. The+-- stub records every request (including its headers and decoded JSON),+-- counts streams the client closed before the server finished them, and+-- offers one push channel that feeds every open "channel" event stream,+-- which the HTTP+SSE fixture uses to deliver replies.+module McpStub+ ( Stub (..),+ StubRequest (..),+ StubReply (..),+ SseStep (..),+ withStub,++ -- * Inspecting requests+ rpcMethod,+ rpcId,+ rpcParams,+ rpcMeta,+ header,++ -- * Building replies+ ok,+ okResult,+ rpcErrorReply,+ rpcErrorBody,+ sseMessage,+ sseResult,+ discoverResultObject,+ discover,++ -- * A strict modern server+ modernServer,+ ModernHandler,+ methodsOf,++ -- * Test support+ fastLimits,+ config,+ connectOrFail,+ expectErr,+ waitFor,+ )+where++import Baikai.Mcp.Client++import Baikai.Mcp.Transport (decodeHeaderValue)+import Control.Concurrent (threadDelay)+import Control.Concurrent.STM+import Control.Exception (SomeException, finally, try)+import Control.Monad (forM_, forever)+import Data.Aeson (Value (..), object, (.=))+import Data.Aeson qualified as Aeson+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Object, Pair)+import Data.ByteString (ByteString)+import Data.ByteString.Builder qualified as Builder+import Data.ByteString.Lazy qualified as LBS+import Data.CaseInsensitive qualified as CI+import Data.IORef+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.Encoding qualified as TE+import Network.HTTP.Types (Header, RequestHeaders, mkStatus)+import Network.Wai qualified as Wai+import Network.Wai.Handler.Warp qualified as Warp+import Test.Tasty.HUnit (Assertion, assertFailure)++data StubRequest = StubRequest+ { httpMethod :: !ByteString,+ path :: !ByteString,+ query :: !ByteString,+ headers :: !RequestHeaders,+ body :: !LBS.ByteString,+ json :: !(Maybe Value)+ }+ deriving stock (Show)++data SseStep+ = -- | Raw bytes, written and flushed.+ Chunk !ByteString+ | Pause !Int+ | -- | Keep the stream open, sending comment keep-alives, until the+ -- client disconnects.+ HoldOpen++data StubReply+ = ReplyJson !Int ![Header] !Value+ | ReplyRaw !Int ![Header] !LBS.ByteString+ | ReplySse !Int ![Header] ![SseStep]+ | -- | An event stream fed by 'push' until the client disconnects.+ ReplyChannel !Int ![Header] ![ByteString]++data Stub = Stub+ { url :: !Text,+ requests :: IO [StubRequest],+ -- | Event streams the client closed while the server still had more to+ -- send or was holding them open.+ clientClosed :: IO Int,+ -- | Feed bytes to every open channel stream.+ push :: ByteString -> IO ()+ }++withStub :: (Stub -> StubRequest -> IO StubReply) -> (Stub -> IO a) -> IO a+withStub handler action = do+ ref <- newIORef []+ closedCount <- newIORef (0 :: Int)+ chan <- newBroadcastTChanIO+ stubRef <- newIORef (error "stub not ready")+ let app request respond = do+ bytes <- Wai.strictRequestBody request+ let captured =+ StubRequest+ { httpMethod = Wai.requestMethod request,+ path = Wai.rawPathInfo request,+ query = Wai.rawQueryString request,+ headers = Wai.requestHeaders request,+ body = bytes,+ json = Aeson.decode bytes+ }+ atomicModifyIORef' ref (\xs -> (xs <> [captured], ()))+ stub <- readIORef stubRef+ reply <- handler stub captured+ case reply of+ ReplyJson code hs v ->+ respond (Wai.responseLBS (mkStatus code "stub") (("Content-Type", "application/json") : hs) (Aeson.encode v))+ ReplyRaw code hs b -> respond (Wai.responseLBS (mkStatus code "stub") hs b)+ ReplySse code hs steps ->+ respond . Wai.responseStream (mkStatus code "stub") (("Content-Type", "text/event-stream") : hs) $ \write flush -> do+ r <- try @SomeException $ forM_ steps $ \case+ Chunk b -> write (Builder.byteString b) >> flush+ Pause n -> threadDelay n+ HoldOpen -> forever (write (Builder.byteString ":\n") >> flush >> threadDelay 20000)+ case r of+ Left _ -> atomicModifyIORef' closedCount (\n -> (n + 1, ()))+ Right () -> pure ()+ ReplyChannel code hs initial -> do+ sub <- atomically (dupTChan chan)+ respond . Wai.responseStream (mkStatus code "stub") (("Content-Type", "text/event-stream") : hs) $ \write flush -> do+ r <- try @SomeException $ do+ forM_ initial $ \b -> write (Builder.byteString b) >> flush+ forever $ do+ next <- atomically (tryReadTChan sub)+ case next of+ Just b -> write (Builder.byteString b) >> flush+ Nothing -> write (Builder.byteString ":\n") >> flush >> threadDelay 20000+ case r of+ Left _ -> atomicModifyIORef' closedCount (\n -> (n + 1, ()))+ Right () -> pure ()+ Warp.testWithApplication (pure app) $ \port -> do+ let stub =+ Stub+ { url = "http://127.0.0.1:" <> Text.pack (show port) <> "/mcp",+ requests = readIORef ref,+ clientClosed = readIORef closedCount,+ push = \b -> atomically (writeTChan chan b)+ }+ writeIORef stubRef stub+ action stub `finally` pure ()++-- ---------------------------------------------------------------------------+-- Inspecting++rpcMethod :: StubRequest -> Maybe Text+rpcMethod r = case r.json of+ Just (Object o) | Just (String m) <- KeyMap.lookup "method" o -> Just m+ _ -> Nothing++rpcId :: StubRequest -> Value+rpcId r = case r.json of+ Just (Object o) | Just i <- KeyMap.lookup "id" o -> i+ _ -> Null++rpcParams :: StubRequest -> Object+rpcParams r = case r.json of+ Just (Object o) | Just (Object p) <- KeyMap.lookup "params" o -> p+ _ -> KeyMap.empty++rpcMeta :: StubRequest -> Object+rpcMeta r = case KeyMap.lookup "_meta" (rpcParams r) of+ Just (Object m) -> m+ _ -> KeyMap.empty++header :: ByteString -> StubRequest -> Maybe ByteString+header n r = lookup (CI.mk n) r.headers++-- | Method names, or the HTTP verb for requests without a JSON-RPC body.+methodsOf :: [StubRequest] -> [Text]+methodsOf = map (\r -> maybe (TE.decodeUtf8 r.httpMethod) id (rpcMethod r))++-- ---------------------------------------------------------------------------+-- Building++ok :: Value -> StubReply+ok = ReplyJson 200 []++-- | A result response to the request.+okResult :: StubRequest -> [Pair] -> StubReply+okResult r fields = ok (object ["jsonrpc" .= ("2.0" :: Text), "id" .= rpcId r, "result" .= object fields])++rpcErrorBody :: Value -> Int -> Text -> Maybe Value -> Value+rpcErrorBody i c m d =+ object+ [ "jsonrpc" .= ("2.0" :: Text),+ "id" .= i,+ "error" .= object (["code" .= c, "message" .= m] <> maybe [] (\x -> ["data" .= x]) d)+ ]++rpcErrorReply :: Int -> StubRequest -> Int -> Text -> Maybe Value -> StubReply+rpcErrorReply status r c m d = ReplyJson status [] (rpcErrorBody (rpcId r) c m d)++sseMessage :: Value -> ByteString+sseMessage v = "event: message\ndata: " <> LBS.toStrict (Aeson.encode v) <> "\n\n"++sseResult :: StubRequest -> [Pair] -> ByteString+sseResult r fields = sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "id" .= rpcId r, "result" .= object fields])++discoverResultObject :: [Pair]+discoverResultObject =+ [ "resultType" .= ("complete" :: Text),+ "supportedVersions" .= ["2026-07-28" :: Text],+ "capabilities" .= object ["tools" .= object ["listChanged" .= True], "resources" .= object [], "prompts" .= object []],+ "_meta" .= object ["io.modelcontextprotocol/serverInfo" .= object ["name" .= ("stub" :: Text), "version" .= ("1.0.0" :: Text)]],+ "instructions" .= ("stub instructions" :: Text),+ "ttlMs" .= (60000 :: Int),+ "cacheScope" .= ("public" :: Text)+ ]++-- | The standard discovery answer.+discover :: StubRequest -> StubReply+discover r = okResult r discoverResultObject++-- ---------------------------------------------------------------------------+-- A strict modern server++-- | Handles a validated modern request: method and params.+type ModernHandler = Stub -> StubRequest -> Text -> Object -> IO StubReply++-- | Reject anything a 2026-07-28 server must reject — handshake requests,+-- missing per-request metadata, routing headers that disagree with the+-- body — and answer @server/discover@ unless the handler does.+modernServer :: ModernHandler -> Stub -> StubRequest -> IO StubReply+modernServer handler stub r+ | r.httpMethod /= "POST" = pure (ReplyRaw 405 [] "")+ | otherwise = case rpcMethod r of+ Nothing -> pure (rpcErrorReply 400 r (-32600) "invalid request" Nothing)+ Just "initialize" -> pure (rpcErrorReply 400 r (-32601) "initialize is not supported; this server speaks 2026-07-28" Nothing)+ Just m -> case validate m of+ Just problem -> pure (rpcErrorReply 400 r (-32020) problem Nothing)+ Nothing -> handler stub r m (rpcParams r)+ where+ validate m =+ let meta = rpcMeta r+ version = case KeyMap.lookup "io.modelcontextprotocol/protocolVersion" meta of+ Just (String v) -> Just v+ _ -> Nothing+ nameField = case m of+ "tools/call" -> Just "name"+ "prompts/get" -> Just "name"+ "resources/read" -> Just "uri"+ _ -> Nothing+ bodyName =+ nameField >>= \k -> case KeyMap.lookup (Key.fromText k) (rpcParams r) of+ Just (String s) -> Just s+ _ -> Nothing+ headerName = header "Mcp-Name" r >>= either (const Nothing) Just . decodeHeaderValue+ in firstProblem+ [ (version == Nothing, "missing protocolVersion in _meta"),+ (not (KeyMap.member "io.modelcontextprotocol/clientCapabilities" meta), "missing clientCapabilities in _meta"),+ (fmap TE.decodeUtf8 (header "MCP-Protocol-Version" r) /= version, "MCP-Protocol-Version does not match _meta"),+ (fmap TE.decodeUtf8 (header "Mcp-Method" r) /= Just m, "Mcp-Method does not match the body"),+ (headerName /= bodyName, "Mcp-Name does not match the body"),+ (header "Mcp-Session-Id" r /= Nothing, "a modern request must not carry a session")+ ]+ firstProblem = foldr (\(bad, why) rest -> if bad then Just why else rest) Nothing++-- ---------------------------------------------------------------------------+-- Test support++fastLimits :: McpLimits+fastLimits = defaultMcpLimits {requestTimeout = 2, connectTimeout = 2}++config :: Stub -> McpServerConfig+config stub = (mcpServerConfig "stub" stub.url) {limits = fastLimits}++connectOrFail :: McpServerConfig -> IO McpConnection+connectOrFail cfg = do+ r <- connectMcp cfg+ case r of+ Left e -> assertFailure ("connect failed: " <> show e) >> error "unreachable"+ Right c -> pure c++expectErr :: Either McpError a -> IO McpError+expectErr = \case+ Left e -> pure e+ Right _ -> assertFailure "expected an error" >> error "unreachable"++-- | Poll a condition every 20 ms, up to @n@ times.+waitFor :: Int -> IO Bool -> Assertion+waitFor 0 _ = assertFailure "condition not reached"+waitFor n cond = do+ ok' <- cond+ if ok' then pure () else threadDelay 20000 >> waitFor (n - 1) cond
+ test/ModernHttpSpec.hs view
@@ -0,0 +1,242 @@+module ModernHttpSpec (tests) where++import Baikai.Mcp.Client+import Baikai.Mcp.Protocol+import Baikai.Mcp.Transport (paramHeader)+import Data.Aeson (Value (..), object, (.=))+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Object)+import Data.ByteString qualified as BS+import Data.IORef+import Data.Map.Strict qualified as Map+import Data.Text (Text)+import McpStub+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++tests :: TestTree+tests =+ testGroup+ "Modern Streamable HTTP"+ [ discovery,+ errors,+ continuation,+ interruption,+ routing+ ]++discovery :: TestTree+discovery =+ testGroup+ "discovery"+ [ testCase "discovery succeeds without initialize and headers match the body" $+ withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else rpcErrorReply 404 r (-32601) "no" Nothing))) $ \stub -> do+ c <- connectOrFail (config stub)+ connectionEra c @?= Modern latestModernVersion+ let d = connectionDescription c+ d.serverInfo @?= Just (implementation "stub" "1.0.0")+ d.instructions @?= Just "stub instructions"+ d.cache @?= Just (CacheHint 60000 CachePublic)+ assertBool "tools capability" (capabilityPresent "tools" d.capabilities)+ rs <- stub.requests+ methodsOf rs @?= ["server/discover"]+ map (header "Accept") rs @?= [Just "application/json, text/event-stream"]+ KeyMap.lookup "io.modelcontextprotocol/clientInfo" (rpcMeta (rs !! 0)) @?= Just (object ["name" .= ("baikai-mcp" :: Text), "version" .= ("0.1.0.0" :: Text)])+ closeMcp c,+ testCase "the same discovery result arrives over split SSE frames" $ do+ viaJson <- withStub (modernServer (\_ r _ _ -> pure (discover r))) $ \stub ->+ connectionDescription <$> connectOrFail (config stub)+ viaSse <- withStub+ ( modernServer $ \_ r _ _ -> do+ let frame = sseResult r discoverResultObject+ (a, b) = BS.splitAt 23 frame+ progress = sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "method" .= ("notifications/message" :: Text), "params" .= object ["level" .= ("info" :: Text), "data" .= ("hi" :: Text)]])+ pure (ReplySse 200 [] [Chunk ":\n\n", Chunk progress, Chunk a, Pause 20000, Chunk b])+ )+ $ \stub -> connectionDescription <$> connectOrFail (config stub)+ viaSse @?= viaJson+ ]++errors :: TestTree+errors =+ testGroup+ "errors"+ [ testCase "an unsupported version is an incompatibility, not a fallback" $+ withStub (modernServer (\_ r _ _ -> pure (rpcErrorReply 400 r (-32022) "Unsupported protocol version" (Just (object ["supported" .= ["2099-01-01" :: Text], "requested" .= ("2026-07-28" :: Text)]))))) $ \stub -> do+ e <- connectMcp (config stub) >>= expectErr+ e.kind @?= IncompatibleServer+ methodsOf <$> stub.requests >>= (@?= ["server/discover"]),+ testCase "a missing client capability stays modern" $+ withStub (modernServer (\_ r _ _ -> pure (rpcErrorReply 400 r (-32021) "Missing capability" (Just (object ["requiredCapabilities" .= object ["roots" .= object []]]))))) $ \stub -> do+ e <- connectMcp (config stub) >>= expectErr+ e.kind @?= RemoteRpcError+ fmap (.code) e.rpc @?= Just (-32021)+ e.httpStatus @?= Just 400+ methodsOf <$> stub.requests >>= (@?= ["server/discover"]),+ testCase "a header mismatch rejection is reported with its code" $+ withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else rpcErrorReply 400 r (-32020) "Header mismatch" Nothing))) $ \stub -> do+ c <- connectOrFail (config stub)+ e <- callMethod c (mcpCall "tools/list" KeyMap.empty) >>= expectErr+ fmap (.code) e.rpc @?= Just (-32020)+ e.delivery @?= Answered,+ testCase "a response with an unrelated id is malformed and uncertain" $+ withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else ok (object ["jsonrpc" .= ("2.0" :: Text), "id" .= (999 :: Int), "result" .= object []])))) $ \stub -> do+ c <- connectOrFail (config stub)+ e <- callMethod c (mcpCall "tools/list" KeyMap.empty) >>= expectErr+ e.kind @?= MalformedReply+ e.delivery @?= Uncertain,+ testCase "an oversized response is refused" $+ withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else okResult r ["tools" .= [String (mconcat (replicate 4000 "x"))]]))) $ \stub -> do+ c <- connectOrFail (config stub) {limits = fastLimits {maxResponseBytes = 1024}}+ e <- callMethod c (mcpCall "tools/list" KeyMap.empty) >>= expectErr+ e.kind @?= LimitExceeded,+ testCase "a stream that ends before its response is a lost reply" $+ withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else ReplySse 200 [] [Chunk ":\n\n"]))) $ \stub -> do+ c <- connectOrFail (config stub)+ e <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "echo")])) >>= expectErr+ e.kind @?= TransportFailure+ e.delivery @?= Uncertain,+ testCase "a denied request transmits nothing" $+ withStub (modernServer (\_ r _ _ -> pure (discover r))) $ \stub -> do+ let hook = McpRequestHook $ \att -> pure (if att.method == "tools/call" then SendDenied "not approved" else SendAllowed [])+ c <- connectOrFail (config stub) {requestHook = hook}+ e <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "echo")])) >>= expectErr+ e.kind @?= RequestDenied+ e.delivery @?= NotSent+ methodsOf <$> stub.requests >>= (@?= ["server/discover"]),+ testCase "a credential challenge never downgrades" $+ withStub (\_ _ -> pure (ReplyRaw 401 [("WWW-Authenticate", "Bearer resource_metadata=\"https://x/.well-known\"")] "")) $ \stub -> do+ e <- connectMcp (config stub) >>= expectErr+ e.httpStatus @?= Just 401+ e.challenge @?= Just "Bearer resource_metadata=\"https://x/.well-known\""+ methodsOf <$> stub.requests >>= (@?= ["server/discover"]),+ testCase "a redirect is not followed" $+ withStub (\_ _ -> pure (ReplyRaw 307 [("Location", "http://127.0.0.1:1/elsewhere")] "")) $ \stub -> do+ e <- connectMcp (config stub) >>= expectErr+ e.kind @?= HttpFailure+ e.httpStatus @?= Just 307+ length <$> stub.requests >>= (@?= 1)+ ]++-- | A tools/call that needs @rounds@ state-only rounds before completing.+statefulTool :: Int -> IORef [Object] -> ModernHandler+statefulTool rounds seen _ r m p = case m of+ "server/discover" -> pure (discover r)+ "tools/call" -> do+ modifyIORef' seen (<> [p])+ n <- length <$> readIORef seen+ pure $+ if n > rounds+ then okResult r ["resultType" .= ("complete" :: Text), "content" .= [object ["type" .= ("text" :: Text), "text" .= ("done" :: Text)]]]+ else okResult r ["resultType" .= ("input_required" :: Text), "requestState" .= ("opaque/state+" <> show n <> "==")]+ _ -> pure (rpcErrorReply 404 r (-32601) "no" Nothing)++toolCall :: McpCall+toolCall = mcpCall "tools/call" (KeyMap.fromList [("name", "slow_tool"), ("arguments", object ["x" .= (1 :: Int)])])++continuation :: TestTree+continuation =+ testGroup+ "interim results"+ [ testCase "two state-only rounds complete with three distinct requests" $ do+ seen <- newIORef []+ withStub (modernServer (statefulTool 2 seen)) $ \stub -> do+ c <- connectOrFail (config stub)+ r <- callInteractive c toolCall+ case r of+ Right (McpCompleted cr) -> do+ cr.continuationRounds @?= 2+ cr.cache @?= Nothing+ other -> assertFailure (show other)+ calls <- filter ((== Just "tools/call") . rpcMethod) <$> stub.requests+ length calls @?= 3+ let ids = map rpcId calls+ assertBool "distinct ids" (length ids == length (foldr (\x acc -> if x `elem` acc then acc else x : acc) [] ids))+ map (KeyMap.lookup "requestState" . rpcParams) calls+ @?= [Nothing, Just "opaque/state+1==", Just "opaque/state+2=="]+ let stripped = map (KeyMap.delete "requestState" . rpcParams) calls+ assertBool "identical parameters" (and (zipWith (==) stripped (drop 1 stripped)))+ map (header "Mcp-Name") calls @?= replicate 3 (Just "slow_tool"),+ testCase "a denied continuation stops with the state and sends nothing more" $ do+ seen <- newIORef []+ withStub (modernServer (statefulTool 2 seen)) $ \stub -> do+ let hook = McpRequestHook $ \att -> pure $ case att.purpose of+ PurposeContinuation _ -> SendDenied "host stopped the loop"+ _ -> SendAllowed []+ c <- connectOrFail (config stub) {requestHook = hook}+ r <- callInteractive c toolCall+ case r of+ Right (McpUnfinished u) -> do+ u.requestState @?= Just "opaque/state+1=="+ assertBool "denied" (case u.reason of ContinuationDenied _ -> True; _ -> False)+ other -> assertFailure (show other)+ length <$> readIORef seen >>= (@?= 1),+ testCase "a spent round limit stops with the typed outcome" $ do+ seen <- newIORef []+ withStub (modernServer (statefulTool 10 seen)) $ \stub -> do+ c <- connectOrFail (config stub) {limits = fastLimits {maxContinuationRounds = 1}}+ r <- callInteractive c toolCall+ fmap (fmap (.reason)) (unfinishedOf r) @?= Just (Just RoundLimitReached)+ length <$> readIORef seen >>= (@?= 2),+ testCase "a zero round limit disables continuation" $ do+ seen <- newIORef []+ withStub (modernServer (statefulTool 1 seen)) $ \stub -> do+ c <- connectOrFail (config stub) {limits = fastLimits {maxContinuationRounds = 0}}+ r <- callInteractive c toolCall+ fmap (fmap (.reason)) (unfinishedOf r) @?= Just (Just RoundLimitReached)+ length <$> readIORef seen >>= (@?= 1),+ testCase "input requests are returned unanswered"+ $ withStub+ ( modernServer $ \_ r m _ ->+ pure $+ if m == "server/discover"+ then discover r+ else okResult r ["resultType" .= ("input_required" :: Text), "inputRequests" .= object ["login" .= object ["method" .= ("elicitation/create" :: Text)]], "requestState" .= ("s" :: Text)]+ )+ $ \stub -> do+ c <- connectOrFail (config stub)+ r <- callInteractive c toolCall+ case r of+ Right (McpUnfinished u) -> do+ u.reason @?= NeedsClientInput+ u.requestState @?= Just "s"+ fmap Map.size u.inputRequests @?= Just 1+ other -> assertFailure (show other)+ length . filter ((== Just "tools/call") . rpcMethod) <$> stub.requests >>= (@?= 1)+ ]+ where+ unfinishedOf = \case+ Right (McpUnfinished u) -> Just (Just u)+ _ -> Nothing++interruption :: TestTree+interruption =+ testCase "an interrupted call reaches the server once and closes its stream"+ $ withStub+ ( modernServer $ \_ r m _ ->+ pure $+ if m == "server/discover"+ then discover r+ else ReplySse 200 [] [Chunk (sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "method" .= ("notifications/progress" :: Text), "params" .= object ["progressToken" .= (1 :: Int), "progress" .= (1 :: Int)]])), HoldOpen]+ )+ $ \stub -> do+ c <- connectOrFail (config stub) {limits = fastLimits {requestTimeout = 0.4}}+ notes <- newIORef (0 :: Int)+ e <- callMethod c toolCall {onNotification = Just (\_ _ -> modifyIORef' notes (+ 1))} >>= expectErr+ e.kind @?= TimedOut+ e.delivery @?= Uncertain+ readIORef notes >>= (@?= 1)+ waitFor 50 ((>= 1) <$> stub.clientClosed)+ length . filter ((== Just "tools/call") . rpcMethod) <$> stub.requests >>= (@?= 1)++routing :: TestTree+routing =+ testCase "names and parameter mirrors are encoded into headers" $+ withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else okResult r ["content" .= ([] :: [Value])]))) $ \stub -> do+ c <- connectOrFail (config stub)+ region <- either (\e -> assertFailure (show e) >> error "unreachable") (maybe (assertFailure "no mirror" >> error "unreachable") pure) (paramHeader "Region" (Just "Hello, 世界"))+ _ <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "天気"), ("arguments", object ["region" .= ("Hello, 世界" :: Text)])])) {paramHeaders = [region]}+ calls <- filter ((== Just "tools/call") . rpcMethod) <$> stub.requests+ map (header "Mcp-Name") calls @?= [Just "=?base64?5aSp5rCX?="]+ map (header "Mcp-Param-Region") calls @?= [Just "=?base64?SGVsbG8sIOS4lueVjA==?="]+ map (header "Mcp-Method") calls @?= [Just "tools/call"]
+ test/ProtocolSpec.hs view
@@ -0,0 +1,202 @@+module ProtocolSpec (tests) where++import Baikai.Mcp.Internal.Sse+import Baikai.Mcp.Protocol+import Baikai.Mcp.Transport+import Data.Aeson (Value (..), object, (.=))+import Data.Aeson qualified as Aeson+import Data.Aeson.KeyMap qualified as KeyMap+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.Either (isLeft)+import Data.IORef+import Data.Map.Strict qualified as Map+import Data.Text (Text)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++tests :: TestTree+tests =+ testGroup+ "Protocol"+ [ envelopes,+ resultKinds,+ cacheHints,+ headerValues,+ paramMirrors,+ sseParsing,+ draining+ ]++obj :: [(Aeson.Key, Value)] -> KeyMap.KeyMap Value+obj = KeyMap.fromList++envelopes :: TestTree+envelopes =+ testGroup+ "JSON-RPC envelopes"+ [ testCase "a request carries version, id, method and params" $+ encodeRequest (RequestIdNumber 7) "tools/list" (obj [("cursor", "c")])+ @?= object ["jsonrpc" .= ("2.0" :: Text), "id" .= (7 :: Int), "method" .= ("tools/list" :: Text), "params" .= object ["cursor" .= ("c" :: Text)]],+ testCase "a notification has no id and omits empty params" $+ encodeNotification "notifications/initialized" KeyMap.empty+ @?= object ["jsonrpc" .= ("2.0" :: Text), "method" .= ("notifications/initialized" :: Text)],+ testCase "a frame with both result and error is rejected" $+ assertBool "rejected" . isLeft $+ decodeMessage (object ["jsonrpc" .= ("2.0" :: Text), "id" .= (1 :: Int), "result" .= object [], "error" .= object ["code" .= (1 :: Int), "message" .= ("x" :: Text)]]),+ testCase "a frame without jsonrpc 2.0 is rejected" $+ assertBool "rejected" . isLeft $+ decodeMessage (object ["id" .= (1 :: Int), "result" .= object []]),+ testCase "a null request id is rejected" $+ assertBool "rejected" . isLeft $+ decodeMessage (object ["jsonrpc" .= ("2.0" :: Text), "id" .= Null, "method" .= ("ping" :: Text)]),+ testCase "string and integer ids decode" $ do+ decodeMessage (object ["jsonrpc" .= ("2.0" :: Text), "id" .= ("a" :: Text), "result" .= object []])+ @?= Right (IncomingResponse (Just (RequestIdText "a")) (Right KeyMap.empty))+ decodeMessage (object ["jsonrpc" .= ("2.0" :: Text), "id" .= (3 :: Int), "error" .= object ["code" .= (-32601 :: Int), "message" .= ("no" :: Text)]])+ @?= Right (IncomingResponse (Just (RequestIdNumber 3)) (Left (rpcError (-32601) "no"))),+ testCase "_meta merges with protocol fields winning" $ do+ let merged = withRequestMeta (requestMeta latestModernVersion Nothing) (obj [("_meta", object ["traceparent" .= ("t" :: Text), "io.modelcontextprotocol/protocolVersion" .= ("old" :: Text)])])+ KeyMap.lookup "_meta" merged+ @?= Just+ ( object+ [ "traceparent" .= ("t" :: Text),+ "io.modelcontextprotocol/protocolVersion" .= ("2026-07-28" :: Text),+ "io.modelcontextprotocol/clientCapabilities" .= object []+ ]+ ),+ testCase "unsupported-version data lists the offered versions" $+ unsupportedVersionsOffered (RpcError (-32022) "x" (Just (object ["supported" .= ["2026-07-28", "2025-11-25" :: Text], "requested" .= ("1900-01-01" :: Text)])))+ @?= Just [ProtocolVersion "2026-07-28", ProtocolVersion "2025-11-25"]+ ]++resultKinds :: TestTree+resultKinds =+ testGroup+ "result types"+ [ testCase "complete and absent resultType are complete" $ do+ decodeResultKind "tools/list" (obj [("resultType", "complete")]) @?= Right ResultComplete+ decodeResultKind "tools/list" KeyMap.empty @?= Right ResultComplete,+ testCase "state-only input_required on tools/call" $+ decodeResultKind "tools/call" (obj [("resultType", "input_required"), ("requestState", "s1")])+ @?= Right (ResultInputRequired (InputRequired Nothing (Just "s1"))),+ testCase "input requests and state" $+ decodeResultKind "prompts/get" (obj [("resultType", "input_required"), ("inputRequests", object ["a" .= object ["method" .= ("roots/list" :: Text)]]), ("requestState", "s")])+ @?= Right (ResultInputRequired (InputRequired (Just (Map.fromList [("a", object ["method" .= ("roots/list" :: Text)])])) (Just "s"))),+ testCase "input_required with neither field is invalid" $+ assertBool "rejected" . isLeft $+ decodeResultKind "resources/read" (obj [("resultType", "input_required")]),+ testCase "input_required on a method that does not allow it is invalid" $+ assertBool "rejected" . isLeft $+ decodeResultKind "tools/list" (obj [("resultType", "input_required"), ("requestState", "s")]),+ testCase "an unknown resultType is invalid" $+ assertBool "rejected" . isLeft $+ decodeResultKind "tools/call" (obj [("resultType", "task")])+ ]++cacheHints :: TestTree+cacheHints =+ testGroup+ "cache hints"+ [ testCase "public and private hints decode; negative ttl clamps to zero" $ do+ decodeCacheHint (obj [("ttlMs", Number 5000), ("cacheScope", "private")]) @?= Right (Just (CacheHint 5000 CachePrivate))+ decodeCacheHint (obj [("ttlMs", Number (-4)), ("cacheScope", "public")]) @?= Right (Just (CacheHint 0 CachePublic)),+ testCase "absent hints are Nothing" $ decodeCacheHint KeyMap.empty @?= Right Nothing,+ testCase "an unknown scope or a lone field is invalid" $ do+ assertBool "scope" . isLeft $ decodeCacheHint (obj [("ttlMs", Number 1), ("cacheScope", "shared")])+ assertBool "lone" . isLeft $ decodeCacheHint (obj [("ttlMs", Number 1)])+ ]++-- | The encoding table from the 2026-07-28 Streamable HTTP page.+headerValues :: TestTree+headerValues =+ testGroup+ "header value encoding"+ [ testCase "plain ASCII passes through" $ encodeHeaderValue "us-west1" @?= "us-west1",+ testCase "non-ASCII is Base64-wrapped" $ encodeHeaderValue "Hello, 世界" @?= "=?base64?SGVsbG8sIOS4lueVjA==?=",+ testCase "leading or trailing whitespace is Base64-wrapped" $ encodeHeaderValue " padded " @?= "=?base64?IHBhZGRlZCA=?=",+ testCase "a newline is Base64-wrapped" $ encodeHeaderValue "line1\nline2" @?= "=?base64?bGluZTEKbGluZTI=?=",+ testCase "a sentinel-shaped literal is Base64-wrapped" $ encodeHeaderValue "=?base64?literal?=" @?= "=?base64?PT9iYXNlNjQ/bGl0ZXJhbD89?=",+ testCase "decoding inverts encoding" $+ mapM_ (\t -> decodeHeaderValue (encodeHeaderValue t) @?= Right t) ["us-west1", "Hello, 世界", " padded ", "line1\nline2", "=?base64?literal?=", ""]+ ]++paramMirrors :: TestTree+paramMirrors =+ testGroup+ "parameter mirrors"+ [ testCase "string, integer and boolean values" $ do+ fmap (fmap paramHeaderValue) (paramHeader "Region" (Just "us-west1")) @?= Right (Just "us-west1")+ fmap (fmap paramHeaderValue) (paramHeader "Count" (Just (Number 42))) @?= Right (Just "42")+ fmap (fmap paramHeaderValue) (paramHeader "Neg" (Just (Number (-7)))) @?= Right (Just "-7")+ fmap (fmap paramHeaderValue) (paramHeader "Flag" (Just (Bool False))) @?= Right (Just "false")+ fmap (fmap paramHeaderField) (paramHeader "Region" (Just "x")) @?= Right (Just "Mcp-Param-Region"),+ testCase "null and absent values are omitted" $ do+ paramHeader "Region" (Just Null) @?= Right Nothing+ paramHeader "Region" Nothing @?= Right Nothing,+ testCase "unsafe integers, fractions, arrays and invalid names are refused" $ do+ assertBool "unsafe" . isLeft $ paramHeader "N" (Just (Number (2 ^ (53 :: Int))))+ assertBool "fraction" . isLeft $ paramHeader "N" (Just (Number 1.5))+ assertBool "array" . isLeft $ paramHeader "N" (Just (Aeson.toJSON [1 :: Int]))+ assertBool "name" . isLeft $ paramHeader "bad name" (Just "x")+ assertBool "empty" . isLeft $ paramHeader "" (Just "x")+ ]++feedAll :: Int -> [ByteString] -> Either String [SseEvent]+feedAll lim = go (newSseParser lim) []+ where+ go _ acc [] = Right (concat (reverse acc))+ go p acc (c : cs) = case feedSse p c of+ Left e -> Left e+ Right (p', evs) -> go p' (evs : acc) cs++sseParsing :: TestTree+sseParsing =+ testGroup+ "server-sent events"+ [ testCase "events split across chunks at every byte reassemble" $ do+ let stream = ": keepalive\r\nevent: message\r\ndata: {\"a\":\r\ndata: 1}\r\n\r\ndata: two\n\n"+ expected = [SseEvent "message" "{\"a\":\n1}", SseEvent "" "two"]+ feedAll 1024 [stream] @?= Right expected+ feedAll 1024 (map BS.singleton (BS.unpack stream)) @?= Right expected,+ testCase "a CR at the end of a chunk followed by LF is one line break" $+ feedAll 1024 ["data: x\r", "\n\r", "\n"] @?= Right [SseEvent "" "x"],+ testCase "an incomplete event at end of input is not dispatched" $+ feedAll 1024 ["data: x\n"] @?= Right [],+ testCase "an oversized line or event is refused" $ do+ assertBool "line" . isLeft $ feedAll 8 ["data: 0123456789"]+ assertBool "event" . isLeft $ feedAll 11 ["data: 12345\ndata: 12345\n\n"]+ ]++draining :: TestTree+draining =+ testGroup+ "bounded drain"+ [ testCase "pages are concatenated in order" $ do+ let pages = Map.fromList [(Nothing, page [1, 2] (Just "a")), (Just "a", page [3] (Just "")), (Just "", page [4] Nothing)]+ r <- drainPages defaultDrainLimits (\c -> pure (Right @Text (pages Map.! fmap cursorToText c)))+ r @?= Right [1, 2, 3, 4 :: Int],+ testCase "a repeated cursor stops the drain" $ do+ r <- drainPages defaultDrainLimits (\_ -> pure (Right @Text (page [1 :: Int] (Just "same"))))+ r @?= Left (DrainRepeatedCursor 2),+ testCase "the page limit is enforced before the next fetch" $ do+ calls <- newIORef (0 :: Int)+ r <- drainPages defaultDrainLimits {maxPages = 2} $ \c -> do+ modifyIORef' calls (+ 1)+ n <- readIORef calls+ pure (Right @Text (page [n] (Just (maybe "0" (const (if n == 1 then "x" else "y")) c))))+ r @?= Left (DrainTooManyPages 2)+ readIORef calls >>= (@?= 2),+ testCase "item and byte ceilings" $ do+ r1 <- drainPages defaultDrainLimits {maxItems = 2} (\_ -> pure (Right @Text (page [1, 2, 3 :: Int] Nothing)))+ r1 @?= Left (DrainTooManyItems 3)+ r2 <- drainPages defaultDrainLimits {maxBytes = 5} (\_ -> pure (Right @Text (page [1 :: Int] Nothing) {responseBytes = 10}))+ r2 @?= Left (DrainTooManyBytes 10),+ testCase "a fetch failure names the page" $ do+ r <- drainPages defaultDrainLimits (\c -> pure (maybe (Right (page [1 :: Int] (Just "n"))) (const (Left ("boom" :: Text))) c))+ case r of+ Left (DrainPageFailed 2 "boom") -> pure ()+ other -> assertFailure (show other)+ ]+ where+ page xs c = Page {items = xs, nextCursor = cursorFromText <$> c, cache = Nothing, responseBytes = 1}
+ test/ResourcePromptSpec.hs view
@@ -0,0 +1,261 @@+module ResourcePromptSpec (tests) where++import Baikai.Content (TextContent (..), UserContent (..))+import Baikai.Mcp.Client+import Baikai.Mcp.Content+import Baikai.Mcp.Prompt+import Baikai.Mcp.Protocol+import Baikai.Mcp.Resource+import Baikai.Message (Message (..), UserPayload (..))+import Data.Aeson (Value (..), object, (.=))+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Pair)+import Data.IORef+import Data.Text (Text)+import Data.Vector qualified as Vector+import McpStub+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++tests :: TestTree+tests =+ testGroup+ "Resources and prompts"+ [ resources,+ prompts,+ updates+ ]++cacheFields :: [Pair]+cacheFields = ["resultType" .= ("complete" :: Text), "ttlMs" .= (5000 :: Int), "cacheScope" .= ("private" :: Text)]++resourceServer :: IORef Int -> ModernHandler+resourceServer reads' _ r m p = case m of+ "server/discover" -> pure (discover r)+ "resources/list" -> pure $ case KeyMap.lookup "cursor" p of+ Nothing -> okResult r (cacheFields <> ["resources" .= [res "file:///a.txt" "a"], "nextCursor" .= ("next==" :: Text)])+ Just "next==" -> okResult r (cacheFields <> ["resources" .= [res "db://rows/1" "row"]])+ Just _ -> okResult r (cacheFields <> ["resources" .= ([] :: [Value]), "nextCursor" .= ("next==" :: Text)])+ "resources/templates/list" -> pure (okResult r (cacheFields <> ["resourceTemplates" .= [object ["uriTemplate" .= ("db://rows/{id}" :: Text), "name" .= ("rows" :: Text)]]]))+ "resources/read" -> case KeyMap.lookup "uri" p of+ Just "file:///mixed" ->+ pure . okResult r $+ cacheFields+ <> [ "contents"+ .= [ object ["uri" .= ("file:///mixed#1" :: Text), "mimeType" .= ("text/plain" :: Text), "text" .= ("hello" :: Text)],+ object ["uri" .= ("file:///mixed#2" :: Text), "mimeType" .= ("image/png" :: Text), "blob" .= ("iVBORw==" :: Text)]+ ]+ ]+ Just "file:///empty" -> pure (okResult r (cacheFields <> ["contents" .= ([] :: [Value])]))+ Just "file:///badblob" -> pure (okResult r (cacheFields <> ["contents" .= [object ["uri" .= ("file:///badblob" :: Text), "blob" .= ("!!not base64!!" :: Text)]]]))+ Just "file:///bigblob" -> pure (okResult r (cacheFields <> ["contents" .= [object ["uri" .= ("file:///bigblob" :: Text), "blob" .= ("QUJDREVGR0g=" :: Text)]]]))+ Just "file:///missing" -> pure (rpcErrorReply 200 r (-32602) "Resource not found" (Just (object ["uri" .= ("file:///missing" :: Text)])))+ Just "file:///old-missing" -> pure (rpcErrorReply 200 r (-32002) "Resource not found" Nothing)+ Just "file:///bad-params" -> pure (rpcErrorReply 200 r (-32602) "uri must be absolute" Nothing)+ Just "file:///slow" -> do+ n <- atomicModifyIORef' reads' (\x -> (x + 1, x + 1))+ pure $+ if n == 1+ then okResult r ["resultType" .= ("input_required" :: Text), "requestState" .= ("again" :: Text)]+ else okResult r (cacheFields <> ["contents" .= [object ["uri" .= ("file:///slow" :: Text), "text" .= ("done" :: Text)]]])+ _ -> pure (rpcErrorReply 200 r (-32602) "Resource not found" (Just (object ["uri" .= KeyMap.lookup "uri" p])))+ _ -> pure (rpcErrorReply 404 r (-32601) "Method not found" Nothing)+ where+ res :: Text -> Text -> Value+ res u n = object ["uri" .= u, "name" .= n, "mimeType" .= ("text/plain" :: Text)]++readOk :: McpConnection -> Text -> IO ResourceRead+readOk c u = do+ r <- readResource c u+ case r of+ Right (McpCompleted rr) -> pure rr+ other -> assertFailure (show other) >> error "unreachable"++resources :: TestTree+resources =+ testGroup+ "resources"+ [ testCase "two pages follow the opaque cursor and carry cache hints" $ do+ n <- newIORef 0+ withStub (modernServer (resourceServer n)) $ \stub -> do+ c <- connectOrFail (config stub)+ p1 <- listResources c Nothing+ case p1 of+ Right p -> do+ map (.uri) p.items @?= ["file:///a.txt"]+ p.cache @?= Just (CacheHint 5000 CachePrivate)+ Left e -> assertFailure (show e)+ r <- listAllResources c defaultDrainLimits+ fmap (map (.name)) r @?= Right ["a", "row"]+ t <- listAllResourceTemplates c defaultDrainLimits+ fmap (map (.uriTemplate)) t @?= Right ["db://rows/{id}"],+ testCase "a repeated cursor stops the listing" $ do+ n <- newIORef 0+ withStub+ (modernServer (\s r m p -> if m == "resources/list" then pure (okResult r (cacheFields <> ["resources" .= ([] :: [Value]), "nextCursor" .= ("same" :: Text)])) else resourceServer n s r m p))+ $ \stub -> do+ c <- connectOrFail (config stub)+ r <- listAllResources c defaultDrainLimits+ case r of+ Left (DrainRepeatedCursor 2) -> pure ()+ other -> assertFailure (show other),+ testCase "a read preserves every item with its URI, type and bytes" $ do+ n <- newIORef 0+ withStub (modernServer (resourceServer n)) $ \stub -> do+ c <- connectOrFail (config stub)+ rr <- readOk c "file:///mixed"+ map (.uri) rr.contents @?= ["file:///mixed#1", "file:///mixed#2"]+ map (.mimeType) rr.contents @?= [Just "text/plain", Just "image/png"]+ map (.body) rr.contents @?= [TextBody "hello", BlobBody "\137PNG"]+ rr.cache @?= Just (CacheHint 5000 CachePrivate)+ reads' <- filter ((== Just "resources/read") . rpcMethod) <$> stub.requests+ map (header "Mcp-Name") reads' @?= [Just "file:///mixed"],+ testCase "an existing empty resource is not an error" $ do+ n <- newIORef 0+ withStub (modernServer (resourceServer n)) $ \stub -> do+ c <- connectOrFail (config stub)+ rr <- readOk c "file:///empty"+ rr.contents @?= [],+ testCase "missing resources are distinguished from other invalid parameters" $ do+ n <- newIORef 0+ withStub (modernServer (resourceServer n)) $ \stub -> do+ c <- connectOrFail (config stub)+ readResource c "file:///missing" >>= \case+ Left (ResourceNotFound _) -> pure ()+ other -> assertFailure (show other)+ readResource c "file:///old-missing" >>= \case+ Left (ResourceNotFound _) -> pure ()+ other -> assertFailure (show other)+ readResource c "file:///bad-params" >>= \case+ Left (ResourceRequestFailed e) -> fmap (.message) e.rpc @?= Just "uri must be absolute"+ other -> assertFailure (show other),+ testCase "invalid and oversized blobs are bounded errors" $ do+ n <- newIORef 0+ withStub (modernServer (resourceServer n)) $ \stub -> do+ c <- connectOrFail (config stub)+ readResource c "file:///badblob" >>= \case+ Left (ResourceMalformed _) -> pure ()+ other -> assertFailure (show other)+ readResourceWith c ReadOptions {maxBlobChars = 4} "file:///bigblob" >>= \case+ Left (ResourceMalformed _) -> pure ()+ other -> assertFailure (show other),+ testCase "a server without resources reports method not found" $+ withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else rpcErrorReply 404 r (-32601) "Method not found" Nothing))) $ \stub -> do+ c <- connectOrFail (config stub)+ readResource c "file:///a" >>= \case+ Left (ResourceRequestFailed e) -> fmap (.code) e.rpc @?= Just (-32601)+ other -> assertFailure (show other),+ testCase "a state-only interim read completes and is not cacheable" $ do+ n <- newIORef 0+ withStub (modernServer (resourceServer n)) $ \stub -> do+ c <- connectOrFail (config stub)+ rr <- readOk c "file:///slow"+ rr.continuationRounds @?= 1+ rr.cache @?= Nothing,+ testCase "a legacy server's read without modern fields" $+ withStub legacyHandler $ \stub -> do+ c <- connectOrFail (config stub) {profile = McpLegacyStreamableHttp}+ rr <- readOk c "file:///a"+ map (.body) rr.contents @?= [TextBody "legacy"]+ rr.cache @?= Nothing+ p <- listResources c Nothing+ fmap (.cache) p @?= Right Nothing+ ]+ where+ legacyHandler _ r = pure $ case rpcMethod r of+ Just "initialize" -> okResult r ["protocolVersion" .= ("2025-06-18" :: Text), "capabilities" .= object ["resources" .= object []]]+ Just "notifications/initialized" -> ReplyRaw 202 [] ""+ Just "resources/read" -> okResult r ["contents" .= [object ["uri" .= ("file:///a" :: Text), "text" .= ("legacy" :: Text)]]]+ Just "resources/list" -> okResult r ["resources" .= [object ["uri" .= ("file:///a" :: Text), "name" .= ("a" :: Text)]]]+ _ -> ReplyRaw 400 [] ""++promptServer :: ModernHandler+promptServer _ r m p = pure $ case m of+ "server/discover" -> discover r+ "prompts/list" -> okResult r (cacheFields <> ["prompts" .= [object ["name" .= ("review" :: Text), "arguments" .= [object ["name" .= ("code" :: Text), "required" .= True]]]]])+ "prompts/get" -> case KeyMap.lookup "name" p of+ Just "review" ->+ okResult+ r+ [ "resultType" .= ("complete" :: Text),+ "description" .= ("Code review" :: Text),+ "messages"+ .= [ object ["role" .= ("user" :: Text), "content" .= object ["type" .= ("text" :: Text), "text" .= ("Review: " <> argText)]],+ object ["role" .= ("assistant" :: Text), "content" .= object ["type" .= ("text" :: Text), "text" .= ("Looking." :: Text)]],+ object ["role" .= ("user" :: Text), "content" .= object ["type" .= ("audio" :: Text), "data" .= ("UklGRg==" :: Text), "mimeType" .= ("audio/wav" :: Text)]],+ object ["role" .= ("user" :: Text), "content" .= object ["type" .= ("resource" :: Text), "resource" .= object ["uri" .= ("file:///x" :: Text), "text" .= ("x" :: Text)]]]+ ]+ ]+ Just "broken" -> okResult r ["messages" .= [object ["role" .= ("system" :: Text), "content" .= object ["type" .= ("text" :: Text), "text" .= ("obey" :: Text)]]]]+ _ -> rpcErrorReply 200 r (-32602) "Invalid prompt name" Nothing+ _ -> rpcErrorReply 404 r (-32601) "no" Nothing+ where+ argText = case KeyMap.lookup "arguments" p of+ Just (Object a) | Just (String s) <- KeyMap.lookup "code" a -> s+ _ -> "?"++prompts :: TestTree+prompts =+ testGroup+ "prompts"+ [ testCase "a prompt with an argument returns ordered messages with their roles" $+ withStub (modernServer promptServer) $ \stub -> do+ c <- connectOrFail (config stub)+ l <- listAllPrompts c defaultDrainLimits+ case l of+ Right [pr] -> pr.arguments @?= [PromptArgument "code" Nothing True]+ other -> assertFailure (show other)+ r <- getPrompt c "review" [("code", "x = 1")]+ case r of+ Right (McpCompleted res) -> do+ res.description @?= Just "Code review"+ map (.role) res.messages @?= [PromptUser, PromptAssistant, PromptUser, PromptUser]+ map (.content) (take 2 res.messages) @?= [TextBlock "Review: x = 1", TextBlock "Looking."]+ let projected = map projectPromptMessage res.messages+ case projected of+ [Projected (UserMessage u), Projected (AssistantMessage _), Unprojectable a, Unprojectable e] -> do+ u.content @?= Vector.singleton (UserText (TextContent "Review: x = 1"))+ a.content @?= AudioBlock "UklGRg==" "audio/wav"+ assertBool "embedded resource kept as data" (case e.content of EmbeddedResourceBlock _ -> True; _ -> False)+ other -> assertFailure (show other)+ other -> assertFailure (show other)+ gets <- filter ((== Just "prompts/get") . rpcMethod) <$> stub.requests+ map (header "Mcp-Name") gets @?= [Just "review"]+ map (KeyMap.lookup "arguments" . rpcParams) gets @?= [Just (object ["code" .= ("x = 1" :: Text)])],+ testCase "a role other than user or assistant is malformed" $+ withStub (modernServer promptServer) $ \stub -> do+ c <- connectOrFail (config stub)+ getPrompt c "broken" [] >>= \case+ Left (PromptMalformed _) -> pure ()+ other -> assertFailure (show other),+ testCase "an unknown prompt keeps the server's invalid-params error" $+ withStub (modernServer promptServer) $ \stub -> do+ c <- connectOrFail (config stub)+ getPrompt c "nope" [] >>= \case+ Left (PromptRequestFailed e) -> fmap (.code) e.rpc @?= Just (-32602)+ other -> assertFailure (show other)+ ]++updates :: TestTree+updates =+ testCase "resource updates arrive on a subscription and a reread is explicit" $ do+ n <- newIORef 0+ withStub (modernServer (handler n)) $ \stub -> do+ c <- connectOrFail (config stub)+ r <- withResourceUpdates c ["file:///mixed"] False $ \sub -> do+ (subscriptionAcknowledged sub).resourceSubscriptions @?= ["file:///mixed"]+ nextResourceEvent sub+ r @?= Right (ResourceUpdated "file:///mixed")+ connectionOpenListeners c >>= (@?= 0)+ waitFor 50 ((>= 1) <$> stub.clientClosed)+ before <- length . filter ((== Just "resources/read") . rpcMethod) <$> stub.requests+ before @?= 0+ _ <- readOk c "file:///mixed"+ closeMcp c+ where+ handler n s r m p+ | m == "subscriptions/listen" =+ let sid = rpcId r+ note method extra = sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "method" .= (method :: Text), "params" .= object (("_meta" .= object ["io.modelcontextprotocol/subscriptionId" .= sid]) : extra)])+ in pure (ReplySse 200 [] [Chunk (note "notifications/subscriptions/acknowledged" ["notifications" .= object ["resourceSubscriptions" .= ["file:///mixed" :: Text]]]), Chunk (note "notifications/resources/updated" ["uri" .= ("file:///mixed" :: Text)]), HoldOpen])+ | otherwise = resourceServer n s r m p
+ test/StreamSpec.hs view
@@ -0,0 +1,428 @@+module StreamSpec (tests) where++import Baikai.Mcp.Client+import Baikai.Mcp.Protocol+import Baikai.Mcp.Tool+import Baikai.Mcp.Transport.Stream+import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (Async, async, cancel, poll, wait)+import Control.Concurrent.STM+import Control.Exception (bracket, finally)+import Control.Monad (forM_, when)+import Data.Aeson (Value (..), object, (.=))+import Data.Aeson qualified as Aeson+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Object)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Char8 qualified as BS8+import Data.IORef+import Data.Text (Text)+import McpStub (waitFor)+import System.IO (hClose, hFlush)+import System.Process (createPipe)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++tests :: TestTree+tests =+ testGroup+ "Caller-owned streams"+ [ framing,+ eras,+ lifecycle,+ handles+ ]++-- ---------------------------------------------------------------------------+-- In-memory pipes and scripted servers++data Pipe = Pipe+ { client :: McpStream,+ toServer :: TQueue (Maybe ByteString),+ toClient :: TQueue (Maybe ByteString),+ readsInFlight :: IORef Int,+ clientClosedIt :: IORef Bool+ }++newPipe :: IO Pipe+newPipe = do+ c2s <- newTQueueIO+ s2c <- newTQueueIO+ inflight <- newIORef 0+ closed <- newIORef False+ let readChunk = do+ atomicModifyIORef' inflight (\n -> (n + 1, ()))+ (maybe "" id <$> atomically (readTQueue s2c)) `finally` atomicModifyIORef' inflight (\n -> (n - 1, ()))+ pure+ Pipe+ { client =+ McpStream+ { readChunk = readChunk,+ writeChunk = \b -> atomically (writeTQueue c2s (Just b)),+ closeStream = Just (writeIORef closed True >> atomically (writeTQueue c2s Nothing))+ },+ toServer = c2s,+ toClient = s2c,+ readsInFlight = inflight,+ clientClosedIt = closed+ }++data Server = Server+ { received :: IORef [Value],+ send :: Value -> IO (),+ sendRaw :: ByteString -> IO (),+ closeOutput :: IO ()+ }++-- | Run a line-oriented server over the pipe until the client closes it.+runServer :: Pipe -> (Server -> Value -> IO ()) -> IO (Server, Async ())+runServer p handler = do+ rec' <- newIORef []+ let srv =+ Server+ { received = rec',+ send = \v -> atomically (writeTQueue p.toClient (Just (BS.toStrict (Aeson.encode v) <> "\n"))),+ sendRaw = \b -> atomically (writeTQueue p.toClient (Just b)),+ closeOutput = atomically (writeTQueue p.toClient Nothing)+ }+ loop buffered = case BS8.elemIndex '\n' buffered of+ Just i -> do+ let line = BS.take i buffered+ case Aeson.decodeStrict line of+ Just v -> modifyIORef' rec' (<> [v]) >> handler srv v+ Nothing -> pure ()+ loop (BS.drop (i + 1) buffered)+ Nothing -> do+ chunk <- atomically (readTQueue p.toServer)+ case chunk of+ Nothing -> pure ()+ Just c -> loop (buffered <> c)+ a <- async (loop BS.empty)+ pure (srv, a)++field :: Aeson.Key -> Value -> Maybe Value+field k = \case+ Object o -> KeyMap.lookup k o+ _ -> Nothing++paramsOf :: Value -> Object+paramsOf v = case field "params" v of+ Just (Object o) -> o+ _ -> KeyMap.empty++methodOf :: Value -> Maybe Text+methodOf v = case field "method" v of+ Just (String m) -> Just m+ _ -> Nothing++reply :: Value -> [(Aeson.Key, Value)] -> Value+reply req fields = object ["jsonrpc" .= ("2.0" :: Text), "id" .= field "id" req, "result" .= object fields]++replyError :: Value -> Int -> Text -> Maybe Value -> Value+replyError req c m d = object ["jsonrpc" .= ("2.0" :: Text), "id" .= field "id" req, "error" .= object (["code" .= c, "message" .= m] <> maybe [] (\x -> ["data" .= x]) d)]++toolsPage :: Value -> Object -> Value+toolsPage req p = case KeyMap.lookup "cursor" p of+ Nothing -> reply req ["tools" .= [tool "echo"], "nextCursor" .= ("2" :: Text)]+ Just _ -> reply req ["tools" .= [tool "other"]]+ where+ tool :: Text -> Value+ tool n = object ["name" .= n, "inputSchema" .= object ["type" .= ("object" :: Text), "properties" .= object ["msg" .= object ["type" .= ("string" :: Text), "x-mcp-header" .= ("Msg" :: Text)]]]]++echoResult :: Value -> Object -> Value+echoResult req p =+ let msg = case KeyMap.lookup "arguments" p of+ Just (Object a) | Just (String m) <- KeyMap.lookup "msg" a -> m+ _ -> "?"+ in reply req ["content" .= [object ["type" .= ("text" :: Text), "text" .= msg]]]++-- | A 2026-07-28 server: rejects initialize, requires per-request _meta.+modernStdio :: Server -> Value -> IO ()+modernStdio srv msg = case (methodOf msg, field "id" msg) of+ (Just "notifications/cancelled", _) -> pure ()+ (Just _, Nothing) -> pure ()+ (Just "initialize", Just _) -> srv.send (replyError msg (-32601) "Method not found: this server speaks 2026-07-28 (initialize is not supported)" Nothing)+ (Just m, Just _)+ | not (hasMeta msg) -> srv.send (replyError msg (-32602) "missing _meta" Nothing)+ | otherwise -> case m of+ "server/discover" -> srv.send (reply msg ["resultType" .= ("complete" :: Text), "supportedVersions" .= ["2026-07-28" :: Text], "capabilities" .= object ["tools" .= object []]])+ "tools/list" -> srv.send (toolsPage msg (paramsOf msg))+ "tools/call" -> case KeyMap.lookup "name" (paramsOf msg) of+ Just "echo" -> srv.send (echoResult msg (paramsOf msg))+ Just "stateful"+ | KeyMap.member "requestState" (paramsOf msg) -> srv.send (reply msg ["content" .= ([] :: [Value])])+ | otherwise -> srv.send (reply msg ["resultType" .= ("input_required" :: Text), "requestState" .= ("s" :: Text)])+ Just "slow" -> pure ()+ Just "die" -> srv.closeOutput+ Just "huge" -> srv.sendRaw (BS8.replicate 4096 'x' <> "\n")+ Just "garbage" -> srv.sendRaw "this is not json\n"+ _ -> srv.send (replyError msg (-32602) "unknown tool" Nothing)+ "subscriptions/listen" -> do+ let sid = field "id" msg+ filt = KeyMap.lookup "notifications" (paramsOf msg)+ note method extra = srv.send (object ["jsonrpc" .= ("2.0" :: Text), "method" .= (method :: Text), "params" .= object (("_meta" .= object ["io.modelcontextprotocol/subscriptionId" .= sid]) : extra)])+ note "notifications/subscriptions/acknowledged" ["notifications" .= filt]+ case filt of+ Just f | Just (Bool True) <- field "toolsListChanged" f -> note "notifications/tools/list_changed" []+ Just f | Just (Array us) <- field "resourceSubscriptions" f -> forM_ us $ \u -> note "notifications/resources/updated" ["uri" .= u]+ _ -> pure ()+ _ -> srv.send (replyError msg (-32601) "Method not found" Nothing)+ _ -> pure ()+ where+ hasMeta v = case KeyMap.lookup "_meta" (paramsOf v) of+ Just (Object meta) -> KeyMap.member "io.modelcontextprotocol/protocolVersion" meta+ _ -> False++-- | A 2025-11-25 server: errors (or stays silent) until initialized, and+-- pings the client once initialized.+legacyStdio :: Bool -> IORef Bool -> Server -> Value -> IO ()+legacyStdio silentProbe initialized srv msg = do+ ready <- readIORef initialized+ case (methodOf msg, field "id" msg) of+ (Nothing, _) -> pure ()+ (Just "notifications/initialized", Nothing) -> do+ writeIORef initialized True+ srv.send (object ["jsonrpc" .= ("2.0" :: Text), "id" .= ("ping-1" :: Text), "method" .= ("ping" :: Text)])+ (Just _, Nothing) -> pure ()+ (Just "initialize", Just _) -> srv.send (reply msg ["protocolVersion" .= ("2025-11-25" :: Text), "capabilities" .= object ["tools" .= object []], "serverInfo" .= object ["name" .= ("old" :: Text), "version" .= ("1" :: Text)]])+ (Just m, Just _)+ | not ready -> if silentProbe then pure () else srv.send (replyError msg (-32600) ("server not initialized: " <> m) Nothing)+ | m == "tools/list" -> srv.send (toolsPage msg (paramsOf msg))+ | m == "tools/call" -> srv.send (echoResult msg (paramsOf msg))+ | otherwise -> srv.send (replyError msg (-32601) "Method not found" Nothing)++streamCfg :: McpStreamConfig+streamCfg = (mcpStreamConfig "stdio-fixture") {probeTimeout = 0.3, streamLimits = defaultMcpLimits {requestTimeout = 2, connectTimeout = 3}}++withServer :: (Server -> Value -> IO ()) -> (Pipe -> Server -> IO a) -> IO a+withServer handler k = do+ p <- newPipe+ bracket (runServer p handler) (cancel . snd) $ \(srv, _) -> k p srv++connectOn :: McpStreamConfig -> Pipe -> IO McpConnection+connectOn cfg p = do+ r <- connectMcpStream cfg p.client+ case r of+ Right c -> pure c+ Left e -> assertFailure ("connect failed: " <> show e) >> error "unreachable"++methodsSeen :: Server -> IO [Text]+methodsSeen srv = foldr (\v acc -> maybe acc (: acc) (methodOf v)) [] <$> readIORef srv.received++-- | Identical caller code for every server: list all tools, call one.+exercise :: McpConnection -> IO (Either McpToolError (McpOutcome McpToolResult))+exercise c = do+ listing <- listTools c defaultDrainLimits+ case listing of+ Right l | (t : _) <- [x | x <- l.tools, x.name == "echo"] -> do+ length l.tools @?= 2+ t.headerMirrors @?= []+ callTool c (mcpToolCall t (KeyMap.fromList [("msg", String "line one\nline two")]))+ other -> assertFailure (show other) >> error "unreachable"++-- ---------------------------------------------------------------------------++framing :: TestTree+framing =+ testGroup+ "framing and correlation"+ [ testCase "one compact line per message; embedded newlines stay escaped" $+ withServer modernStdio $ \p srv -> do+ c <- connectOn streamCfg p+ r <- exercise c+ case r of+ Right (McpCompleted res) -> res.content @?= [TextBlock "line one\nline two"]+ other -> assertFailure (show other)+ msgs <- readIORef srv.received+ length msgs @?= 4+ closeMcp c,+ testCase "replies are routed by id when they arrive out of order" $ do+ held <- newIORef []+ let handler srv msg = case (methodOf msg, field "id" msg) of+ (Just "tools/call", Just _) -> do+ modifyIORef' held (msg :)+ pending <- readIORef held+ when (length pending == 2) $ forM_ pending $ \m -> srv.send (echoResult m (paramsOf m))+ _ -> modernStdio srv msg+ withServer handler $ \p _ -> do+ c <- connectOn streamCfg p+ let call msg = callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "echo"), ("arguments", object ["msg" .= (msg :: Text)])]))+ a <- async (call "first")+ threadDelay 20000+ b <- call "second"+ ra <- wait a+ fmap (KeyMap.lookup "content" . (.result)) ra @?= Right (Just (Aeson.toJSON [object ["type" .= ("text" :: Text), "text" .= ("first" :: Text)]]))+ fmap (KeyMap.lookup "content" . (.result)) b @?= Right (Just (Aeson.toJSON [object ["type" .= ("text" :: Text), "text" .= ("second" :: Text)]]))+ closeMcp c+ ]++eras :: TestTree+eras =+ testGroup+ "era detection"+ [ testCase "the same caller code reaches a modern-only server" $+ withServer modernStdio $ \p srv -> do+ c <- connectOn streamCfg p+ connectionEra c @?= Modern latestModernVersion+ _ <- exercise c+ methodsSeen srv >>= (@?= ["server/discover", "tools/list", "tools/list", "tools/call"])+ closeMcp c,+ testCase "the same caller code reaches a handshake-only server" $ do+ ready <- newIORef False+ withServer (legacyStdio False ready) $ \p srv -> do+ c <- connectOn streamCfg p+ connectionEra c @?= Legacy (ProtocolVersion "2025-11-25")+ r <- exercise c+ case r of+ Right (McpCompleted _) -> pure ()+ other -> assertFailure (show other)+ methodsSeen srv >>= (@?= ["server/discover", "initialize", "notifications/initialized", "tools/list", "tools/list", "tools/call"])+ waitFor 50 (any (\v -> field "id" v == Just "ping-1" && field "result" v == Just (object [])) <$> readIORef srv.received)+ closeMcp c,+ testCase "silence to the probe falls back after the timeout" $ do+ ready <- newIORef False+ withServer (legacyStdio True ready) $ \p srv -> do+ c <- connectOn streamCfg p+ connectionEra c @?= Legacy (ProtocolVersion "2025-11-25")+ msgs <- readIORef srv.received+ map methodOf (take 3 msgs) @?= map Just ["server/discover", "notifications/cancelled", "initialize"]+ field "requestId" (Object (paramsOf (msgs !! 1))) @?= field "id" (msgs !! 0)+ closeMcp c,+ testCase "an unsupported-version answer is modern: no fallback" $ do+ let handler srv msg = case methodOf msg of+ Just "server/discover" -> srv.send (replyError msg (-32022) "Unsupported protocol version" (Just (object ["supported" .= ["2099-01-01" :: Text], "requested" .= ("2026-07-28" :: Text)])))+ _ -> modernStdio srv msg+ withServer handler $ \p srv -> do+ r <- connectMcpStream streamCfg p.client+ case r of+ Left e -> e.kind @?= IncompatibleServer+ Right _ -> assertFailure "expected an incompatibility"+ methodsSeen srv >>= (@?= ["server/discover"]),+ testCase "a known legacy server skips the probe; modern-only never sends initialize" $ do+ ready <- newIORef False+ withServer (legacyStdio False ready) $ \p srv -> do+ c <- connectOn streamCfg {streamProfile = StreamLegacyOnly} p+ closeMcp c+ take 1 <$> methodsSeen srv >>= (@?= ["initialize"])+ ready' <- newIORef False+ withServer (legacyStdio False ready') $ \p srv -> do+ r <- connectMcpStream streamCfg {streamProfile = StreamModernOnly} p.client+ case r of+ Left e -> e.kind @?= IncompatibleServer+ Right _ -> assertFailure "expected the legacy server to be refused"+ methodsSeen srv >>= (@?= ["server/discover"])+ ]++lifecycle :: TestTree+lifecycle =+ testGroup+ "cancellation, subscriptions and limits"+ [ testCase "a timed-out call is cancelled once and its late reply is dropped" $ do+ let handler srv msg = do+ modernStdio srv msg+ when (methodOf msg == Just "notifications/cancelled") $+ srv.send (object ["jsonrpc" .= ("2.0" :: Text), "id" .= field "requestId" (Object (paramsOf msg)), "result" .= object ["content" .= ([] :: [Value])]])+ withServer handler $ \p srv -> do+ c <- connectOn streamCfg {streamLimits = defaultMcpLimits {requestTimeout = 0.3, connectTimeout = 3}} p+ e <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "slow")]))+ case e of+ Left err -> err.kind @?= TimedOut+ Right _ -> assertFailure "expected a timeout"+ r <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "echo"), ("arguments", object ["msg" .= ("after" :: Text)])]))+ fmap (KeyMap.lookup "content" . (.result)) r @?= Right (Just (Aeson.toJSON [object ["type" .= ("text" :: Text), "text" .= ("after" :: Text)]]))+ msgs <- readIORef srv.received+ let slowIds = take 1 [field "id" v | v <- msgs, methodOf v == Just "tools/call"]+ [field "requestId" (Object (paramsOf v)) | v <- msgs, methodOf v == Just "notifications/cancelled"] @?= slowIds+ closeMcp c,+ testCase "two subscriptions on one channel each receive only their own notifications" $+ withServer modernStdio $ \p srv -> do+ c <- connectOn streamCfg p+ r <- withSubscription c emptySubscriptionFilter {toolsListChanged = True} $ \a -> do+ rb <- withSubscription c emptySubscriptionFilter {resourceSubscriptions = ["file:///x"]} $ \b -> do+ eb <- nextSubscriptionEvent b+ pure (eb, subscriptionId b)+ ea <- nextSubscriptionEvent a+ pure (ea, rb)+ case r of+ Right (SubscriptionNotification ma _, Right (SubscriptionNotification mb _, bid)) -> do+ ma @?= "notifications/tools/list_changed"+ mb @?= "notifications/resources/updated"+ waitFor 50 $ do+ msgs <- readIORef srv.received+ pure (Just (Aeson.toJSON bid) `elem` [field "requestId" (Object (paramsOf v)) | v <- msgs, methodOf v == Just "notifications/cancelled"])+ other -> assertFailure (show other)+ connectionOpenListeners c >>= (@?= 0)+ closeMcp c,+ testCase "state-only continuation works unchanged" $+ withServer modernStdio $ \p _ -> do+ c <- connectOn streamCfg p+ r <- callInteractive c (mcpCall "tools/call" (KeyMap.fromList [("name", "stateful")]))+ case r of+ Right (McpCompleted cr) -> cr.continuationRounds @?= 1+ other -> assertFailure (show other)+ closeMcp c,+ testCase "an oversized line fails the connection with a bounded error" $+ withServer modernStdio $ \p _ -> do+ c <- connectOn streamCfg {streamLimits = defaultMcpLimits {maxFrameBytes = 1024, requestTimeout = 2}} p+ e <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "huge")]))+ either (\err -> err.kind @?= LimitExceeded) (const (assertFailure "expected a limit error")) e+ e2 <- callMethod c (mcpCall "tools/list" KeyMap.empty)+ either (\err -> err.delivery @?= NotSent) (const (assertFailure "expected the channel to be failed")) e2+ closeMcp c+ readIORef p.readsInFlight >>= (@?= 0)+ readIORef p.clientClosedIt >>= (@?= True),+ testCase "a line that is not JSON fails the waiting request" $+ withServer modernStdio $ \p _ -> do+ c <- connectOn streamCfg p+ e <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "garbage")]))+ either (\err -> err.kind @?= MalformedReply) (const (assertFailure "expected a malformed reply")) e+ closeMcp c,+ testCase "an end of input during a tool call is an uncertain outcome" $+ withServer modernStdio $ \p _ -> do+ c <- connectOn streamCfg p+ let die = either (error . show) id (decodeTool False (object ["name" .= ("die" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text)]]))+ r <- callTool c (mcpToolCall die KeyMap.empty)+ case r of+ Left (ToolRequestFailed e) -> e.delivery @?= Uncertain+ other -> assertFailure (show other)+ closeMcp c+ readIORef p.readsInFlight >>= (@?= 0),+ testCase "a denied send writes nothing and release is idempotent" $+ withServer modernStdio $ \p srv -> do+ let hook = McpRequestHook (\att -> pure (if att.method == "tools/call" then SendDenied "no" else SendAllowed []))+ c <- connectOn streamCfg {streamRequestHook = hook} p+ before <- length <$> readIORef srv.received+ e <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "echo")]))+ either (\err -> err.kind @?= RequestDenied) (const (assertFailure "expected a denial")) e+ after <- length <$> readIORef srv.received+ after @?= before+ closeMcp c+ closeMcp c+ e2 <- callMethod c (mcpCall "tools/list" KeyMap.empty)+ either (\err -> err.kind @?= ConnectionReleased) (const (assertFailure "expected a released handle")) e2+ ]++-- | The handle helper over real OS pipes.+handles :: TestTree+handles =+ testCase "handleStream works over OS pipes and closes the server's input" $ do+ (serverIn, clientOut) <- createPipe+ (clientIn, serverOut) <- createPipe+ p <- newPipe+ let bridgeOut = do+ chunk <- BS.hGetSome serverIn 65536+ if BS.null chunk then atomically (writeTQueue p.toServer Nothing) else atomically (writeTQueue p.toServer (Just chunk)) >> bridgeOut+ bridgeIn = do+ chunk <- atomically (readTQueue p.toClient)+ case chunk of+ Nothing -> hClose serverOut+ Just b -> BS.hPut serverOut b >> hFlush serverOut >> bridgeIn+ bracket (runServer p modernStdio) (cancel . snd) $ \(_, serverThread) -> do+ a1 <- async bridgeOut+ a2 <- async bridgeIn+ r <- withMcpStream streamCfg (handleStream clientIn clientOut) $ \c -> callMethod c (mcpCall "tools/list" KeyMap.empty)+ assertBool "listed over handles" (either (const False) (either (const False) (const True)) r)+ -- Releasing closed the server's input, so the server saw end of input.+ waitFor 50 (maybe False (const True) <$> poll serverThread)+ mapM_ cancel [a1, a2]
+ test/ToolSpec.hs view
@@ -0,0 +1,382 @@+module ToolSpec (tests) where++import Baikai.Content (ImageContent (..), TextContent (..), ToolResultContent (..))+import Baikai.Mcp.Client+import Baikai.Mcp.JsonSchema (SchemaViolation (..))+import Baikai.Mcp.Protocol+import Baikai.Mcp.Tool+import Baikai.Message (ToolResult (..))+import Baikai.Tool (Tool (description, name, parameters))+import Data.Aeson (Value (..), object, (.=))+import Data.Aeson qualified as Aeson+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Object, Pair)+import Data.IORef+import Data.Text (Text)+import Data.Vector qualified as Vector+import McpStub+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++tests :: TestTree+tests =+ testGroup+ "Tools"+ [ descriptors,+ discovery,+ invocation,+ results,+ changes,+ legacy+ ]++-- ---------------------------------------------------------------------------+-- Fixture descriptors++composedInput :: Value+composedInput =+ object+ [ "type" .= ("object" :: Text),+ "$defs" .= object ["unit" .= object ["enum" .= ["c", "f" :: Text]]],+ "properties"+ .= object+ [ "region" .= object ["type" .= ("string" :: Text), "x-mcp-header" .= ("Region" :: Text)],+ "options" .= object ["type" .= ("object" :: Text), "properties" .= object ["count" .= object ["type" .= ("integer" :: Text), "x-mcp-header" .= ("Count" :: Text)]]],+ "unit" .= object ["$ref" .= ("#/$defs/unit" :: Text)],+ "query" .= object ["anyOf" .= [object ["type" .= ("string" :: Text)], object ["type" .= ("null" :: Text)]]]+ ],+ "required" .= ["region" :: Text]+ ]++weatherTool :: Value+weatherTool =+ object+ [ "name" .= ("get_weather" :: Text),+ "title" .= ("Weather" :: Text),+ "inputSchema" .= composedInput,+ "outputSchema"+ .= object+ [ "$defs" .= object ["temp" .= object ["type" .= ("number" :: Text)]],+ "type" .= ("object" :: Text),+ "properties" .= object ["temperature" .= object ["$ref" .= ("#/$defs/temp" :: Text)], "unit" .= object ["enum" .= ["c", "f" :: Text]]],+ "required" .= ["temperature" :: Text],+ "allOf" .= [object ["not" .= object ["required" .= ["error" :: Text]]]]+ ]+ ]++plainTool :: Text -> Value+plainTool n = object ["name" .= n, "inputSchema" .= object ["type" .= ("object" :: Text)]]++badTools :: [Value]+badTools =+ [ object ["name" .= ("on_number" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text), "properties" .= object ["n" .= object ["type" .= ("number" :: Text), "x-mcp-header" .= ("N" :: Text)]]]],+ object ["name" .= ("duplicate" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text), "properties" .= object ["a" .= object ["type" .= ("string" :: Text), "x-mcp-header" .= ("Dup" :: Text)], "b" .= object ["type" .= ("string" :: Text), "x-mcp-header" .= ("dup" :: Text)]]]],+ object ["name" .= ("under_items" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text), "properties" .= object ["xs" .= object ["type" .= ("array" :: Text), "items" .= object ["type" .= ("string" :: Text), "x-mcp-header" .= ("Item" :: Text)]]]]],+ object ["name" .= ("bad_token" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text), "properties" .= object ["a" .= object ["type" .= ("string" :: Text), "x-mcp-header" .= ("Bad Name" :: Text)]]]]+ ]++-- | A modern server with a two-page tool list and a scriptable tools/call.+toolServer :: (StubRequest -> Text -> Object -> IO StubReply) -> ModernHandler+toolServer onCall _ r m p = case m of+ "server/discover" -> pure (discover r)+ "tools/list" -> pure $ case KeyMap.lookup "cursor" p of+ Nothing -> okResult r (listPage (weatherTool : take 2 badTools) (Just "p2"))+ Just "p2" -> okResult r (listPage (plainTool "echo" : drop 2 badTools) Nothing)+ Just _ -> rpcErrorReply 400 r (-32602) "invalid cursor" Nothing+ "tools/call" -> case KeyMap.lookup "name" p of+ Just (String n) -> onCall r n p+ _ -> pure (rpcErrorReply 400 r (-32602) "no name" Nothing)+ _ -> pure (rpcErrorReply 404 r (-32601) "no" Nothing)++listPage :: [Value] -> Maybe Text -> [Pair]+listPage ts next =+ ["resultType" .= ("complete" :: Text), "tools" .= ts, "ttlMs" .= (0 :: Int), "cacheScope" .= ("public" :: Text)]+ <> maybe [] (\c -> ["nextCursor" .= c]) next++completeWith :: [Pair] -> StubRequest -> Text -> Object -> IO StubReply+completeWith fields r _ _ = pure (okResult r (("resultType" .= ("complete" :: Text)) : fields))++discoverTools :: McpConnection -> IO ToolListing+discoverTools c = do+ r <- listTools c defaultDrainLimits+ case r of+ Right l -> pure l+ Left e -> assertFailure (show e) >> error "unreachable"++weatherOf :: ToolListing -> IO McpTool+weatherOf l = case [t | t <- l.tools, t.name == "get_weather"] of+ [t] -> pure t+ _ -> assertFailure "get_weather missing" >> error "unreachable"++completed :: Either McpToolError (McpOutcome McpToolResult) -> IO McpToolResult+completed = \case+ Right (McpCompleted r) -> pure r+ other -> assertFailure ("expected a completed result: " <> show other) >> error "unreachable"++toolCalls :: Stub -> IO [StubRequest]+toolCalls stub = filter ((== Just "tools/call") . rpcMethod) <$> stub.requests++-- ---------------------------------------------------------------------------++descriptors :: TestTree+descriptors =+ testGroup+ "descriptors"+ [ testCase "the input schema survives projection to a model tool verbatim" $+ case decodeTool True weatherTool of+ Right t -> do+ let bt = toBaikaiTool t+ bt.name @?= "get_weather"+ bt.parameters @?= composedInput+ bt.description @?= "Weather"+ t.headerMirrors @?= [HeaderMirror "Count" ["options", "count"], HeaderMirror "Region" ["region"]]+ Left e -> assertFailure (show e),+ testCase "invalid x-mcp-header annotations reject the tool" $+ mapM_ (\v -> assertBool (show v) (either (const True) (const False) (decodeTool True v))) badTools,+ testCase "annotations are ignored where mirrors are not used" $+ mapM_ (\v -> assertBool (show v) (either (const False) (null . (.headerMirrors)) (decodeTool False v))) badTools,+ testCase "an annotation on the root or inside composition is rejected" $ do+ assertBool "root" . either (const True) (const False) $ decodeTool True (object ["name" .= ("r" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text), "x-mcp-header" .= ("Root" :: Text)]])+ assertBool "anyOf" . either (const True) (const False) $+ decodeTool True (object ["name" .= ("c" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text), "anyOf" .= [object ["properties" .= object ["a" .= object ["type" .= ("string" :: Text), "x-mcp-header" .= ("A" :: Text)]]]]]])+ ]++discovery :: TestTree+discovery =+ testGroup+ "discovery"+ [ testCase "two pages are drained; invalid siblings are excluded and reported" $+ withStub (modernServer (toolServer (completeWith []))) $ \stub -> do+ c <- connectOrFail (config stub)+ l <- discoverTools c+ map (.name) l.tools @?= ["get_weather", "echo"]+ map (.toolName) l.rejected @?= map Just ["on_number", "duplicate", "under_items", "bad_token"]+ closeMcp c,+ testCase "a page carries its cache hint and cursor" $+ withStub (modernServer (toolServer (completeWith []))) $ \stub -> do+ c <- connectOrFail (config stub)+ r <- listToolsPage c Nothing+ case r of+ Right tp -> do+ tp.page.cache @?= Just (CacheHint 0 CachePublic)+ fmap cursorToText tp.page.nextCursor @?= Just "p2"+ length tp.rejected @?= 2+ Left e -> assertFailure (show e),+ testCase "a denied second page leaves one request at the server" $+ withStub (modernServer (toolServer (completeWith []))) $ \stub -> do+ let hook = McpRequestHook (\att -> pure (maybe (SendAllowed []) (const (SendDenied "page budget")) att.cursor))+ c <- connectOrFail (config stub) {requestHook = hook}+ r <- listTools c defaultDrainLimits+ case r of+ Left (DrainPageFailed 2 e) -> e.kind @?= RequestDenied+ other -> assertFailure (show other)+ length . filter ((== Just "tools/list") . rpcMethod) <$> stub.requests >>= (@?= 1),+ testCase "a cyclic cursor stops discovery" $+ withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else okResult r (listPage [plainTool "a"] (Just "loop"))))) $ \stub -> do+ c <- connectOrFail (config stub)+ r <- listTools c defaultDrainLimits+ case r of+ Left (DrainRepeatedCursor 2) -> pure ()+ other -> assertFailure (show other),+ testCase "a malformed list response is an error" $+ withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else okResult r ["tools" .= ("nope" :: Text)]))) $ \stub -> do+ c <- connectOrFail (config stub)+ r <- listToolsPage c Nothing+ case r of+ Left e -> e.kind @?= MalformedReply+ Right _ -> assertFailure "expected a malformed reply"+ ]++invocation :: TestTree+invocation =+ testGroup+ "invocation"+ [ testCase "native name, arguments, Unicode and nested mirrors; null mirror omitted" $+ withStub (modernServer (toolServer (completeWith ["content" .= ([] :: [Value]), "structuredContent" .= object ["temperature" .= (21.5 :: Double)]]))) $ \stub -> do+ c <- connectOrFail (config stub)+ t <- discoverTools c >>= weatherOf+ let args = KeyMap.fromList [("region", "東京"), ("options", object ["count" .= Null]), ("unit", "c")]+ r <- callTool c (mcpToolCall t args) >>= completed+ r.outputCheck @?= OutputConforms+ [call] <- toolCalls stub+ KeyMap.lookup "name" (rpcParams call) @?= Just "get_weather"+ KeyMap.lookup "arguments" (rpcParams call) @?= Just (Object args)+ header "Mcp-Name" call @?= Just "get_weather"+ header "Mcp-Param-Region" call @?= Just "=?base64?5p2x5Lqs?="+ header "Mcp-Param-Count" call @?= Nothing,+ testCase "an unmirrorable argument is refused before sending" $+ withStub (modernServer (toolServer (completeWith ["content" .= ([] :: [Value])]))) $ \stub -> do+ c <- connectOrFail (config stub)+ t <- discoverTools c >>= weatherOf+ r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", object [])]))+ case r of+ Left (ToolArgumentsUnmirrorable _) -> pure ()+ other -> assertFailure (show other)+ toolCalls stub >>= (@?= []) . map rpcId,+ testCase "a header-mismatch rejection is descriptor drift and is not retried" $+ withStub (modernServer (toolServer (\r _ _ -> pure (rpcErrorReply 400 r (-32020) "Header mismatch: Mcp-Param-Region" Nothing)))) $ \stub -> do+ c <- connectOrFail (config stub)+ t <- discoverTools c >>= weatherOf+ before <- length <$> stub.requests+ r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", "x")]))+ case r of+ Left (ToolDescriptorDrift e) -> e.delivery @?= Answered+ other -> assertFailure (show other)+ after <- length <$> stub.requests+ after - before @?= 1,+ testCase "a state-only interim result completes on its second round with the same mirrors" $ do+ rounds <- newIORef (0 :: Int)+ let onCall r _ _ = do+ n <- atomicModifyIORef' rounds (\x -> (x + 1, x + 1))+ pure $+ if n == 1+ then okResult r ["resultType" .= ("input_required" :: Text), "requestState" .= ("st" :: Text)]+ else okResult r ["resultType" .= ("complete" :: Text), "content" .= ([] :: [Value]), "structuredContent" .= object ["temperature" .= (1 :: Int)]]+ withStub (modernServer (toolServer onCall)) $ \stub -> do+ c <- connectOrFail (config stub)+ t <- discoverTools c >>= weatherOf+ r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", "eu")])) >>= completed+ r.continuationRounds @?= 1+ calls <- toolCalls stub+ map (header "Mcp-Param-Region") calls @?= [Just "eu", Just "eu"]+ map (KeyMap.lookup "arguments" . rpcParams) calls @?= replicate 2 (Just (object ["region" .= ("eu" :: Text)]))+ map (KeyMap.lookup "requestState" . rpcParams) calls @?= [Nothing, Just "st"],+ testCase "an interim result with input requests is returned unanswered" $+ withStub (modernServer (toolServer (\r _ _ -> pure (okResult r ["resultType" .= ("input_required" :: Text), "inputRequests" .= object ["q" .= object ["method" .= ("sampling/createMessage" :: Text)]]])))) $ \stub -> do+ c <- connectOrFail (config stub)+ t <- discoverTools c >>= weatherOf+ r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", "eu")]))+ case r of+ Right (McpUnfinished u) -> u.reason @?= NeedsClientInput+ other -> assertFailure (show other),+ testCase "a dropped response is uncertain and reaches the server exactly once" $+ withStub (modernServer (toolServer (\_ _ _ -> pure (ReplySse 200 [] [Chunk ":\n\n"])))) $ \stub -> do+ c <- connectOrFail (config stub)+ t <- discoverTools c >>= weatherOf+ r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", "eu")]))+ case r of+ Left (ToolRequestFailed e) -> e.delivery @?= Uncertain+ other -> assertFailure (show other)+ length <$> toolCalls stub >>= (@?= 1)+ ]++results :: TestTree+results =+ testGroup+ "results"+ [ testCase "a composed output-schema violation keeps the result" $+ withStub (modernServer (toolServer (completeWith ["content" .= ([] :: [Value]), "structuredContent" .= object ["temperature" .= ("warm" :: Text), "error" .= True]]))) $ \stub -> do+ c <- connectOrFail (config stub)+ t <- discoverTools c >>= weatherOf+ r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", "eu")]))+ case r of+ Left (ToolOutputViolatesSchema vs res) -> do+ assertBool "type violation" (any ((== "/temperature") . (.instancePath)) vs)+ assertBool "composed violation" (any ((== "not") . (.keyword)) vs)+ res.structured @?= StructuredContent (object ["temperature" .= ("warm" :: Text), "error" .= True])+ other -> assertFailure (show other),+ testCase "a declared schema without structured content cannot be verified" $+ withStub (modernServer (toolServer (completeWith ["content" .= [object ["type" .= ("text" :: Text), "text" .= ("hi" :: Text)]]]))) $ \stub -> do+ c <- connectOrFail (config stub)+ t <- discoverTools c >>= weatherOf+ r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", "eu")]))+ case r of+ Left (ToolOutputUnverifiable _ _) -> pure ()+ other -> assertFailure (show other),+ testCase "structured-only array and present null" $ do+ let arrayTool = object ["name" .= ("arr" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text)], "outputSchema" .= object ["type" .= ("array" :: Text), "items" .= object ["type" .= ("integer" :: Text)]]]+ nullTool = object ["name" .= ("nul" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text)], "outputSchema" .= object ["type" .= ("null" :: Text)]]+ onCall r n _ = pure . okResult r $ ["resultType" .= ("complete" :: Text), "content" .= ([] :: [Value])] <> if n == "arr" then ["structuredContent" .= [1, 2 :: Int]] else ["structuredContent" .= Null]+ withStub (modernServer (\s r m p -> if m == "tools/list" then pure (okResult r (listPage [arrayTool, nullTool] Nothing)) else toolServer onCall s r m p)) $ \stub -> do+ c <- connectOrFail (config stub)+ l <- discoverTools c+ case l.tools of+ [a, n] -> do+ ra <- callTool c (mcpToolCall a KeyMap.empty) >>= completed+ ra.structured @?= StructuredContent (Aeson.toJSON [1, 2 :: Int])+ ra.outputCheck @?= OutputConforms+ (projectToolResult ra).toolResult.content @?= Vector.fromList [ToolResultText (TextContent "[1,2]")]+ rn <- callTool c (mcpToolCall n KeyMap.empty) >>= completed+ rn.structured @?= StructuredContent Null+ rn.outputCheck @?= OutputConforms+ other -> assertFailure (show (map (.name) other)),+ testCase "mixed content is preserved and projection reports what it drops" $ do+ let blocks =+ [ object ["type" .= ("text" :: Text), "text" .= ("hello" :: Text)],+ object ["type" .= ("image" :: Text), "data" .= ("iVBORw==" :: Text), "mimeType" .= ("image/png" :: Text)],+ object ["type" .= ("audio" :: Text), "data" .= ("UklGRg==" :: Text), "mimeType" .= ("audio/wav" :: Text)],+ object ["type" .= ("resource_link" :: Text), "uri" .= ("file:///a" :: Text), "name" .= ("a" :: Text)],+ object ["type" .= ("resource" :: Text), "resource" .= object ["uri" .= ("file:///b" :: Text), "text" .= ("b" :: Text)]],+ object ["type" .= ("hologram" :: Text)]+ ]+ withStub (modernServer (toolServer (completeWith ["content" .= blocks]))) $ \stub -> do+ c <- connectOrFail (config stub)+ l <- discoverTools c+ echo <- case [t | t <- l.tools, t.name == "echo"] of+ [t] -> pure t+ _ -> assertFailure "echo missing" >> error "unreachable"+ r <- callTool c (mcpToolCall echo KeyMap.empty) >>= completed+ length r.content @?= 6+ r.outputCheck @?= NoOutputSchema+ let p = projectToolResult r+ p.toolResult.content @?= Vector.fromList [ToolResultText (TextContent "hello"), ToolResultImage (ImageContent "\137PNG" "image/png")]+ length p.unprojected @?= 4,+ testCase "a tool-reported error is not checked against the output schema" $+ withStub (modernServer (toolServer (completeWith ["content" .= [object ["type" .= ("text" :: Text), "text" .= ("boom" :: Text)]], "isError" .= True]))) $ \stub -> do+ c <- connectOrFail (config stub)+ t <- discoverTools c >>= weatherOf+ r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", "eu")])) >>= completed+ r.isError @?= True+ r.outputCheck @?= NotCheckedToolError+ let (_, dropped) = toolResultMessageFor "call_1" "weather" r+ dropped @?= []+ (projectToolResult r).toolResult.isError @?= True+ ]++changes :: TestTree+changes =+ testCase "a list-change notification never refetches or alters a bound descriptor" $+ withStub (modernServer handler) $ \stub -> do+ c <- connectOrFail (config stub)+ t <- discoverTools c >>= weatherOf+ let call = mcpToolCall t (KeyMap.fromList [("region", "eu")])+ before <- length . filter ((== Just "tools/list") . rpcMethod) <$> stub.requests+ r <- withToolListChanges c $ \sub -> do+ (subscriptionAcknowledged sub).toolsListChanged @?= True+ nextToolListChange sub+ r @?= Right ToolListChanged+ after <- length . filter ((== Just "tools/list") . rpcMethod) <$> stub.requests+ after @?= before+ call.tool @?= t+ where+ handler s r m p+ | m == "subscriptions/listen" =+ let sid = rpcId r+ note method extra = sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "method" .= (method :: Text), "params" .= object (("_meta" .= object ["io.modelcontextprotocol/subscriptionId" .= sid]) : extra)])+ in pure (ReplySse 200 [] [Chunk (note "notifications/subscriptions/acknowledged" ["notifications" .= object ["toolsListChanged" .= True]]), Chunk (note "notifications/tools/list_changed" []), HoldOpen])+ | otherwise = toolServer (completeWith []) s r m p++legacy :: TestTree+legacy =+ testCase "a handshake-era server lists and calls tools with its own shapes" $+ withStub handler $ \stub -> do+ c <- connectOrFail (config stub) {profile = McpLegacyStreamableHttp}+ l <- discoverTools c+ map (.name) l.tools @?= ["on_number"]+ l.rejected @?= []+ case l.tools of+ [t] -> do+ t.headerMirrors @?= []+ r <- callTool c (mcpToolCall t (KeyMap.fromList [("n", Number 1.5)])) >>= completed+ r.content @?= [TextBlock "ok"]+ [call] <- toolCalls stub+ header "Mcp-Param-N" call @?= Nothing+ header "Mcp-Name" call @?= Nothing+ _ -> assertFailure "expected one tool"+ where+ handler _ r = pure $ case rpcMethod r of+ Just "initialize" -> okResult r ["protocolVersion" .= ("2025-11-25" :: Text), "capabilities" .= object ["tools" .= object []]]+ Just "notifications/initialized" -> ReplyRaw 202 [] ""+ Just "tools/list" -> okResult r ["tools" .= take 1 badTools]+ Just "tools/call" -> okResult r ["content" .= [object ["type" .= ("text" :: Text), "text" .= ("ok" :: Text)]]]+ _ -> ReplyRaw 400 [] ""