AI and MCP
id_effect_ai talks to language models the way the rest of the stack talks to databases: the
model is a capability in the typed environment, the vendor is a layer chosen at the edge, every
request goes through the platform HTTP client, and tests run against a deterministic double
instead of a vendor. The crate is tier integration (ADR 0010
Amendment 9) and published from crates/id_effect_ai.
| Feature | What it adds |
|---|---|
openai | OpenAiLanguageModel: Chat Completions (/v1/chat/completions), ChatGPT models and OpenAI-compatible servers |
anthropic | AnthropicLanguageModel: the Messages API (/v1/messages) |
test-util | testing::ScriptedModel, the deterministic double |
cursor | CursorAgentsClient for Cursor Cloud Agents (non-default) |
tools, embeddings, mcp, mcp-http | tool calling, embeddings and MCP (the following chapters) |
Chat
LanguageModel has two methods, complete (a buffered ChatResponse) and complete_stream.
A program does not hold a model; it asks for the capability LanguageModelService with
complete::<R, _>(req) and returns an Effect<ChatResponse, AiError, R>:
#![allow(unused)] fn main() { use id_effect::{Effect, HCons, HNil}; use id_effect_ai::{ AiError, ChatMessage, ChatRequest, LanguageModelService, complete, provide_mock_language_model, }; type Env = HCons<LanguageModelService, HNil>; fn greet(name: &str) -> Effect<String, AiError, Env> { let req = ChatRequest::new( "gpt-4o-mini", vec![ChatMessage::system("Answer in one line."), ChatMessage::user(format!("Greet {name}"))], ); complete::<Env, _>(req).map(|resp| resp.content) } // `provide_mock_language_model` echoes the last user message; production provides a vendor. let out = greet("Ada") .provide_layer(provide_mock_language_model::<AiError>()) .block_on() .into_result() .expect("greet"); assert_eq!(out, "echo:Greet Ada"); }
At the edge the vendor layer replaces the mock. AiConfig::from_env() reads the API keys
(OPENAI_API_KEY, ANTHROPIC_API_KEY) and base URLs, and http_client() builds the platform
client the adapter sends through:
#![allow(unused)] fn main() { use id_effect_ai::{AiConfig, AiError, provide_anthropic_language_model, provide_openai_language_model}; let cfg = AiConfig::from_env(); let openai = provide_openai_language_model::<AiError>(cfg.http_client(), cfg.clone())?; let claude = provide_anthropic_language_model::<AiError>(cfg.http_client(), cfg)?; let _ = (openai, claude); Ok::<(), AiError>(()) }
A ChatResponse carries the text, the token usage (input_tokens, output_tokens), the
vendor's stop_reason (length or max_tokens means the cap was reached) and, for tool calling,
tool_calls. Anthropic's system messages map to its top-level system field.
Streaming
complete_stream returns an id_effect::Stream<CompletionChunk, AiError>: each chunk is a text
delta, and the last one has done set. The vendor adapters decode the server-sent events
incrementally, one body chunk per pull, so the first tokens arrive before the response ends:
#![allow(unused)] fn main() { use id_effect::{HCons, HNil}; use id_effect_ai::{AiError, ChatRequest, LanguageModelService, complete_stream, provide_mock_language_model}; let text: String = complete_stream::<HCons<LanguageModelService, HNil>, _>(ChatRequest::user("m", "stream me")) .provide_layer(provide_mock_language_model::<AiError>()) .flat_map(|stream| stream.run_collect()) .block_on() .into_result() .expect("stream") .iter() .map(|chunk| chunk.delta.as_str()) .collect(); assert_eq!(text, "echo:stream me"); }
Retries, spans and usage
Statuses 429, 502, 503, 504 and Anthropic's 529 ("overloaded") are retried with exponential
backoff (retry_transient_ai_http); 401/403 become AiError::Unauthorized and are not retried.
Every call runs inside an ai.request span with the attributes ai.vendor, ai.operation and
ai.model, and a completion adds ai.usage.input_tokens, ai.usage.output_tokens and
ai.stop_reason, so the OpenTelemetry bridge (chapter 27) exports cost and latency per model
without any prompt text.
Safety defaults
The adapters are secure by default (ADR 0013, ADR 0015 B13 and B14):
- One HTTP client. Every request goes through
id_effect_platform's client, so the 0.11 SSRF policy applies to every provider base URL: a loopback, private, link-local or metadata address fails withAiError::Blockedbefore anything is sent, and redirects are not followed. A self-hosted endpoint (Ollama, a vLLM box) is allowed by name, not by turning the guard off. - Secrets stay secret. API keys are
id_effect_config::Secret;Debugon the config and on the models prints<redacted>. - Prompts are not telemetry. Prompts and completions are never logged or put on a span.
AiConfig::dangerous_log_prompts()turns that on for debugging, and recordsDANGEROUS_LOG_PROMPTSin the posture registry, so the prod posture check refuses to start until the operator accepts it. - Everything is bounded (
AiLimits): every request carriesmax_tokens(1024 unless the request sets its own), a 60 s timeout, a 4 MiB response cap; a stream is capped at 16 MiB and 65 536 events, and one event at 1 MiB. Over a cap the call fails withAiError::LimitExceededand the stream is closed.
#![allow(unused)] fn main() { use std::time::Duration; use id_effect_ai::{AiConfig, AiLimits}; use id_effect_platform::http::HttpClientConfig; let cfg = AiConfig::default() .with_openai_api_key("sk-test") .with_openai_base_url("http://ollama.internal:11434") // Allow the one self-hosted host; every other private address stays refused. .with_http(HttpClientConfig::default().allow_hosts(["ollama.internal"])) .with_limits( AiLimits::default() .with_max_tokens(256) .with_request_timeout(Duration::from_secs(20)), ); assert!(!format!("{cfg:?}").contains("sk-test")); assert!(!cfg.logs_prompts()); }
Testing with ScriptedModel
No test calls a vendor (ADR 0015 D8). testing::ScriptedModel (feature test-util) is a
LanguageModel that answers from a script, in order: text replies, full responses, tool calls,
streams of deltas and failures. It records every request, so a test asserts both what the
program asked and what it did with the answer:
#![allow(unused)] fn main() { use id_effect::{HCons, HNil}; use id_effect_ai::testing::ScriptedModel; use id_effect_ai::{AiError, ChatRequest, LanguageModelService, complete}; type Env = HCons<LanguageModelService, HNil>; let model = ScriptedModel::new() .reply("invoice") .tool_call("call-1", "lookup_customer", serde_json::json!({ "id": 42 })) .fail(AiError::Timeout); let ask = |text: &str| { complete::<Env, _>(ChatRequest::user("any", text)) .provide_layer(model.layer::<AiError>()) .block_on() .into_result() }; assert_eq!(ask("classify").expect("reply").content, "invoice"); assert_eq!(ask("who?").expect("tool call").tool_calls[0].name, "lookup_customer"); assert!(ask("again").is_err()); assert_eq!(model.requests()[0].messages[0].content, "classify"); }
The vendor adapters themselves are tested against recorded fixtures (wiremock) for both vendors, buffered and streamed.
Cursor Cloud Agents
feature = "cursor" exposes CursorAgentsClient, a capability separate from LanguageModel:
list_models, create_agent, send_followup, get_run and wait_until_idle (polls until the
run is terminal or the timeout passes). It authenticates with HTTP Basic (CURSOR_API_KEY) and
goes through the same platform client and limits.