Skip to main content

hyprstream_core/services/
mcp_service.rs

1//! MCP (Model Context Protocol) service — UUID-keyed tool registry
2//!
3//! This service provides an MCP-compliant interface for AI coding assistants
4//! (Claude Code, Cursor, etc.) to interact with hyprstream via:
5//! - HTTP/SSE transport (for web clients with streaming)
6//! - ZMQ control plane (for internal service communication)
7//!
8//! # Architecture
9//!
10//! Tools are registered in a `HashMap<Uuid, ToolEntry>`, announced and called by UUID.
11//! Sync tools return JSON via ZMQ REQ/REP. Streaming tools use `StreamHandle`
12//! (DH + SUB + HMAC verify) to bridge ZMQ streams to MCP SSE.
13//!
14//! # Token Authentication
15//!
16//! The service reads `HYPRSTREAM_TOKEN` from environment (stdio) or
17//! `Authorization: Bearer <token>` header (HTTP) and validates:
18//! 1. JWT signature via Ed25519
19//! 2. Token expiration
20//! 3. Backend services enforce authorization via Casbin policies
21
22use crate::services::generated::mcp_client::{dispatch_mcp, serialize_response, McpHandler};
23use async_trait::async_trait;
24use ed25519_dalek::{SigningKey, VerifyingKey};
25use futures::future::BoxFuture;
26use http::header::AUTHORIZATION;
27use hyprstream_rpc::auth::jwt;
28use hyprstream_rpc::moq_stream::MoqStreamHandle;
29use hyprstream_rpc::service::RequestService;
30use hyprstream_rpc::streaming::StreamPayload;
31use hyprstream_rpc::transport::TransportConfig;
32use hyprstream_rpc_std::mcp_client::{
33    CallTool, ErrorInfo, McpResponseVariant, ServiceMetrics, ServiceStatus, ToolDefinition,
34    ToolList,
35};
36use hyprstream_rpc_std::model_client::ModelClient;
37use hyprstream_rpc_std::policy_client::PolicyCheck;
38use hyprstream_rpc_std::policy_client::PolicyClient;
39use hyprstream_rpc_std::registry_client::RegistryClient;
40use hyprstream_rpc_std::tui_client::TuiClient;
41use hyprstream_rpc_std::workflow_client::WorkflowClient;
42use hyprstream_service::ServiceContext;
43use parking_lot::RwLock;
44use rmcp::{
45    model::{
46        CallToolRequestParams, CallToolResult, Content, ErrorCode, JsonObject, ListToolsResult,
47        PaginatedRequestParams, ServerCapabilities, ServerInfo, Tool, ToolAnnotations,
48    },
49    service::RequestContext,
50    ErrorData, RoleServer, ServerHandler,
51};
52use serde_json::Value;
53use std::borrow::Cow;
54use std::collections::HashMap;
55use std::sync::Arc;
56use tracing::{trace, warn};
57use uuid::Uuid;
58
59// ═══════════════════════════════════════════════════════════════════════════════
60// Service Name
61// ═══════════════════════════════════════════════════════════════════════════════
62
63/// Service name for registration
64pub const SERVICE_NAME: &str = "mcp";
65
66/// UUID v5 namespace for deterministic tool UUIDs
67const MCP_NS: Uuid = Uuid::from_bytes([
68    0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8,
69]);
70
71// b07676df-be7f-56eb-9cd8-e91cfd689158 = UUID v5(MCP_NS, "mcp.refresh_tools")
72const REFRESH_TOOLS_UUID: Uuid = Uuid::from_bytes([
73    0xb0, 0x76, 0x76, 0xdf, 0xbe, 0x7f, 0x56, 0xeb, 0x9c, 0xd8, 0xe9, 0x1c, 0xfd, 0x68, 0x91, 0x58,
74]);
75
76/// JSON-RPC error code returned when MCP authentication fails.
77///
78/// JSON-RPC 2.0 reserves -32099..=-32000 for implementation-defined server
79/// errors; -32001 signals an unauthenticated caller (#1095: fail closed).
80const MCP_AUTH_ERROR: ErrorCode = ErrorCode(-32001);
81
82/// Normalize MCP tool arguments for backend deserialization.
83///
84/// MCP tool schemas expose snake_case parameter names with string types,
85/// but the generated request structs use `#[serde(rename_all = "camelCase")]`
86/// with native numeric types. This function:
87/// 1. Converts object keys from snake_case to camelCase
88/// 2. Coerces string values to numbers/booleans where possible
89fn normalize_mcp_args(value: Value) -> Value {
90    match value {
91        Value::Object(map) => {
92            let converted: serde_json::Map<String, Value> = map
93                .into_iter()
94                .map(|(k, v)| {
95                    let camel = snake_to_camel(&k);
96                    (camel, normalize_mcp_args(v))
97                })
98                .collect();
99            Value::Object(converted)
100        }
101        Value::Array(arr) => Value::Array(arr.into_iter().map(normalize_mcp_args).collect()),
102        Value::String(ref s) if s.is_empty() => value,
103        Value::String(ref s) => {
104            if s == "true" {
105                return Value::Bool(true);
106            }
107            if s == "false" {
108                return Value::Bool(false);
109            }
110            if let Ok(n) = s.parse::<u64>() {
111                return Value::Number(n.into());
112            }
113            if let Ok(n) = s.parse::<i64>() {
114                return Value::Number(n.into());
115            }
116            if let Ok(n) = s.parse::<f64>() {
117                if let Some(num) = serde_json::Number::from_f64(n) {
118                    return Value::Number(num);
119                }
120            }
121            value
122        }
123        other => other,
124    }
125}
126
127fn snake_to_camel(s: &str) -> String {
128    let mut result = String::with_capacity(s.len());
129    let mut capitalize_next = false;
130    for ch in s.chars() {
131        if ch == '_' {
132            capitalize_next = true;
133        } else if capitalize_next {
134            result.extend(ch.to_uppercase());
135            capitalize_next = false;
136        } else {
137            result.push(ch);
138        }
139    }
140    result
141}
142
143// ═══════════════════════════════════════════════════════════════════════════════
144// Configuration
145// ═══════════════════════════════════════════════════════════════════════════════
146
147/// Configuration for McpService
148#[derive(Clone)]
149pub struct McpConfig {
150    /// Ed25519 public key for JWT verification
151    pub verifying_key: VerifyingKey,
152    /// Ed25519 signing key for creating RPC clients
153    pub signing_key: SigningKey,
154    /// RPC transport for control plane
155    pub transport: TransportConfig,
156    /// Policy RPC transport resolved by the factory. This is an IPC socket when
157    /// MCP runs in its own rootless Quadlet process.
158    pub policy_transport: TransportConfig,
159    /// Service context for client construction (optional for backward compat)
160    pub ctx: Option<Arc<ServiceContext>>,
161    /// PolicyService verifying key — used to create the internal PolicyClient
162    /// for peer key resolution and authorization checks.
163    pub policy_verifying_key: VerifyingKey,
164    /// Expected audience (resource URL) for future defense-in-depth
165    pub expected_audience: Option<String>,
166    /// JWT key source for verifying JWTs on ZMQ path (unified local + federated).
167    pub jwt_key_source: Option<std::sync::Arc<dyn hyprstream_rpc::auth::JwtKeySource>>,
168}
169
170// ═══════════════════════════════════════════════════════════════════════════════
171// Tool Registry Types
172// ═══════════════════════════════════════════════════════════════════════════════
173
174/// Handler return type — sync or streaming
175pub enum ToolResult {
176    /// Immediate JSON result (REQ/REP tools)
177    Sync(Value),
178    /// Streaming result — MoqStreamHandle encapsulates DH, moq subscribe, HMAC verification
179    Stream(Box<MoqStreamHandle>),
180}
181
182/// Context passed to handler — carries auth + optional ServiceContext
183pub struct ToolCallContext {
184    pub args: Value,
185    pub signing_key: SigningKey,
186    /// Authenticated user string propagated to backend services
187    pub user: String,
188    /// Authority-verified hosted-account tenant used for the HTTP-face PEP.
189    pub domain: String,
190    /// ServiceContext for typed_client() / client() access (optional for backward compat)
191    pub ctx: Option<Arc<ServiceContext>>,
192    /// Bootstrap Policy client used only for Policy operations.
193    pub policy_client: PolicyClient,
194    /// The verified caller bearer token (MCP stdio/HTTP auth). Forwarded to
195    /// services whose authorization is JWT-backed so they receive the caller's
196    /// identity instead of an anonymous dial (#989 review: workflow dispatch
197    /// was passing `None`, dropping the caller JWT/tenant and forcing
198    /// WorkflowService to reject every `workflow.*` MCP call).
199    pub token: Option<String>,
200}
201
202fn nonempty_mcp_service_token(token: Option<String>) -> anyhow::Result<String> {
203    token
204        .filter(|token| !token.trim().is_empty())
205        .ok_or_else(|| anyhow::anyhow!("MCP service credential is unavailable"))
206}
207
208fn mcp_service_token(signing_key: &SigningKey) -> anyhow::Result<String> {
209    nonempty_mcp_service_token(crate::services::factories::service_token(signing_key))
210}
211
212fn delegated_mcp_bearer(token: Option<&str>) -> anyhow::Result<Option<String>> {
213    match token {
214        Some(token) if token.trim().is_empty() => {
215            anyhow::bail!("MCP caller credential is unavailable")
216        }
217        Some(token) => Ok(Some(token.to_owned())),
218        None => Ok(None),
219    }
220}
221
222fn mcp_model_client(
223    signing_key: &SigningKey,
224    delegated_bearer: Option<&str>,
225) -> anyhow::Result<ModelClient> {
226    let client = ModelClient::from_provider(
227        &hyprstream_discovery::ProductionRpcClientProvider,
228        signing_key.clone(),
229        Some(mcp_service_token(signing_key)?),
230    )?;
231    match delegated_mcp_bearer(delegated_bearer)? {
232        Some(bearer) => Ok(client.with_delegated_bearer(bearer)),
233        None => Ok(client),
234    }
235}
236
237fn mcp_registry_client(
238    signing_key: &SigningKey,
239    delegated_bearer: Option<&str>,
240) -> anyhow::Result<RegistryClient> {
241    let client = RegistryClient::from_provider(
242        &hyprstream_discovery::ProductionRpcClientProvider,
243        signing_key.clone(),
244        Some(mcp_service_token(signing_key)?),
245    )?;
246    match delegated_mcp_bearer(delegated_bearer)? {
247        Some(bearer) => Ok(client.with_delegated_bearer(bearer)),
248        None => Ok(client),
249    }
250}
251
252fn mcp_tui_client(
253    signing_key: &SigningKey,
254    delegated_bearer: Option<&str>,
255) -> anyhow::Result<TuiClient> {
256    let client = TuiClient::from_provider(
257        &hyprstream_discovery::ProductionRpcClientProvider,
258        signing_key.clone(),
259        Some(mcp_service_token(signing_key)?),
260    )?;
261    match delegated_mcp_bearer(delegated_bearer)? {
262        Some(bearer) => Ok(client.with_delegated_bearer(bearer)),
263        None => Ok(client),
264    }
265}
266
267/// Exchange the edge-verified MCP caller token for a short-lived
268/// issuer-audience delegated bearer at the Policy signing boundary
269/// (RFC 8693 shape, same signing call the OAuth token-exchange grant uses).
270///
271/// Registry (like model/tui) is configured with `expected_audience` = the
272/// OAuth issuer URL, and its delegated-relay admission
273/// (`delegated_user_audience`) accepts a relayed user credential only when
274/// the token names that issuer audience. The MCP-edge access token names the
275/// MCP resource URL instead, so forwarding it raw fails envelope audience
276/// verification ("Invalid audience") before any handler or policy check.
277/// Minting here — subject/tenant/scopes/client_id taken from the already
278/// verified token, `dpop_jkt` re-bound to the caller's own key, TTL clamped
279/// to the remaining caller-token lifetime (max 5 minutes) — keeps audience
280/// binding intact: the minted token is issued FOR the resource audience the
281/// registry requires, instead of asking the registry to accept a foreign
282/// audience. The caller's DPoP proof was already verified at the MCP HTTP
283/// edge; the delegated path downstream is the pinned-relay exception that
284/// relies on exactly that ingress verification.
285/// Hard ceiling (seconds) on a minted delegated bearer's lifetime, matching
286/// the mount-ticket TTL (`services/oauth/mount_ticket.rs`).
287const DELEGATED_BEARER_MAX_TTL_SECS: i64 = 300;
288
289/// TTL for the exchanged delegated bearer: the caller token's remaining
290/// lifetime clamped to [`DELEGATED_BEARER_MAX_TTL_SECS`]. Fails closed on an
291/// already-expired caller credential (the edge verification is stale or the
292/// clock skewed — never mint a bearer from it).
293fn delegated_bearer_ttl(exp: i64, now: i64) -> anyhow::Result<u32> {
294    let remaining = exp - now;
295    anyhow::ensure!(remaining > 0, "MCP caller credential has expired");
296    Ok(u32::try_from(remaining.min(DELEGATED_BEARER_MAX_TTL_SECS))
297        .unwrap_or(DELEGATED_BEARER_MAX_TTL_SECS as u32))
298}
299
300async fn delegated_resource_bearer(ctx: &ToolCallContext) -> anyhow::Result<Option<String>> {
301    let Some(token) = ctx.token.as_deref().filter(|t| !t.trim().is_empty()) else {
302        return Ok(None);
303    };
304    // The token was verified by the MCP auth middleware before dispatch;
305    // re-read its signed attributes (never caller-supplied fields) to bind
306    // the exchange to the verified identity.
307    let claims = hyprstream_rpc::auth::decode_unverified(token)
308        .map_err(|e| anyhow::anyhow!("MCP caller credential is undecodable: {e}"))?;
309    // Service credentials already carry their own holder binding and are not
310    // audience-exchanged.
311    if claims.sub.starts_with("service:") {
312        return Ok(Some(token.to_owned()));
313    }
314    let ttl = Some(delegated_bearer_ttl(
315        claims.exp,
316        chrono::Utc::now().timestamp(),
317    )?);
318    let requested_scopes = claims.scope.as_deref().map(|scope| {
319        scope
320            .split_whitespace()
321            .map(str::to_owned)
322            .collect::<Vec<_>>()
323    });
324    let token_info = ctx
325        .policy_client
326        .issue_token(&hyprstream_rpc_std::policy_client::IssueToken {
327            requested_scopes,
328            ttl,
329            // The caller token's verified `iss` is the OAuth issuer URL —
330            // exactly the audience registry's delegated admission requires.
331            audience: Some(claims.iss.clone()),
332            subject: Some(claims.sub.clone()),
333            user_pub_key: None,
334            dpop_jkt: claims.cnf_jkt().map(str::to_owned),
335            issuer: Some(claims.iss.clone()),
336            tenant: claims.tenant.clone(),
337            require_clearance: false,
338            session_id: None,
339            issuance_profile: hyprstream_rpc_std::policy_client::IssueTokenProfile::Rfc8693,
340            client_id: claims.client_id.clone(),
341        })
342        .await
343        .map_err(|e| anyhow::anyhow!("delegated bearer exchange failed: {e}"))?;
344    Ok(Some(token_info.token))
345}
346
347type ToolHandler =
348    Arc<dyn Fn(ToolCallContext) -> BoxFuture<'static, anyhow::Result<ToolResult>> + Send + Sync>;
349
350/// A registered tool
351#[allow(dead_code)]
352struct ToolEntry {
353    uuid: Uuid,
354    name: String,
355    description: String,
356    args_schema: Value,
357    required_scope: String,
358    streaming: bool,
359    handler: ToolHandler,
360}
361
362/// UUID-keyed tool registry
363pub struct ToolRegistry {
364    by_uuid: HashMap<Uuid, ToolEntry>,
365}
366
367impl ToolRegistry {
368    fn new() -> Self {
369        Self {
370            by_uuid: HashMap::new(),
371        }
372    }
373
374    fn register(&mut self, entry: ToolEntry) {
375        self.by_uuid.insert(entry.uuid, entry);
376    }
377
378    fn get(&self, uuid: &Uuid) -> Option<&ToolEntry> {
379        self.by_uuid.get(uuid)
380    }
381
382    fn list(&self) -> impl Iterator<Item = &ToolEntry> {
383        self.by_uuid.values()
384    }
385}
386
387/// Expand the schema's bare `$scope(action)` annotation into the Casbin
388/// action/resource pair used at the HTTP boundary.
389///
390/// Generated RPC authorization receives the bare action separately from its
391/// service resource. MCP metadata preserves only that annotation, so normalize
392/// it once during tool registration instead of rejecting every annotated tool
393/// at dispatch time.
394fn mcp_policy_scope(scope: &str, service_name: &str, method_name: &str) -> String {
395    let operation = if scope.is_empty() { "query" } else { scope };
396    if operation.contains(':') {
397        return operation.to_owned();
398    }
399    let variant = method_name
400        .split('_')
401        .filter(|part| !part.is_empty())
402        .map(|part| {
403            let mut chars = part.chars();
404            chars
405                .next()
406                .map(char::to_uppercase)
407                .into_iter()
408                .flatten()
409                .chain(chars)
410                .collect::<String>()
411        })
412        .collect::<String>();
413    format!("{operation}:{service_name}:{variant}")
414}
415
416// ═══════════════════════════════════════════════════════════════════════════════
417// Tool Registration
418// ═══════════════════════════════════════════════════════════════════════════════
419
420/// Register all tools discovered from schema metadata.
421///
422/// Each service's schema_metadata() + scoped variants are iterated.
423/// Scoped tools are discovered by recursively walking `scoped_client_tree()`.
424/// Scope and streaming flags are read from MethodSchema.
425fn register_schema_tools(reg: &mut ToolRegistry) {
426    use hyprstream_rpc_std::{model_client, policy_client, registry_client, tui_client};
427    // Each service generates its own MethodSchema type, so we use a macro
428    // to iterate each service's methods with the correct type.
429    macro_rules! register_top_level {
430        ($reg:expr, $schema_fn:expr) => {{
431            let (service_name, methods) = $schema_fn;
432            for method in methods {
433                // FIX-7: respect $cliHidden — don't expose internal methods as MCP tools
434                if method.hidden {
435                    continue;
436                }
437                let tool_name = format!("{service_name}.{}", method.name);
438                let params: Vec<(&str, &str, bool, &str)> = method
439                    .params
440                    .iter()
441                    .map(|p| (p.name, p.type_name, p.required, p.description))
442                    .collect();
443                let json_schema = params_to_json_schema(&params);
444                let service_name = service_name.to_string();
445                let method_name = method.name.to_string();
446                let description = if method.description.is_empty() {
447                    format!("{service_name}::{method_name}")
448                } else {
449                    method.description.to_string()
450                };
451                let required_scope = mcp_policy_scope(method.scope, &service_name, &method_name);
452
453                if method.is_streaming {
454                    register_streaming_tool(
455                        $reg,
456                        &tool_name,
457                        description,
458                        json_schema,
459                        required_scope,
460                        service_name,
461                        method_name,
462                    );
463                } else {
464                    register_sync_tool(
465                        $reg,
466                        &tool_name,
467                        description,
468                        json_schema,
469                        required_scope,
470                        service_name,
471                        method_name,
472                    );
473                }
474            }
475        }};
476    }
477
478    register_top_level!(reg, model_client::schema_metadata());
479    register_top_level!(reg, registry_client::schema_metadata());
480    register_top_level!(reg, policy_client::schema_metadata());
481    register_top_level!(reg, tui_client::schema_metadata());
482    register_top_level!(reg, hyprstream_rpc_std::workflow_client::schema_metadata());
483    // Scoped tools: recursive tree walk for all services with nested scopes
484    register_scoped_tools_recursive(
485        reg,
486        "registry",
487        registry_client::scoped_client_tree(),
488        "registry",
489        &[],
490    );
491    register_scoped_tools_recursive(
492        reg,
493        "model",
494        model_client::scoped_client_tree(),
495        "model",
496        &[],
497    );
498}
499
500/// Accumulated scope info: (scope_name, field_name, capnp_type) for building the
501/// `call_scoped_method` scope chain and injecting scope fields into JSON schemas.
502type ScopeInfo = (&'static str, &'static str, &'static str); // (scope_name, field_name, type)
503
504/// Recursively walk the scoped client tree, registering MCP tools at every level.
505///
506/// Each tree node represents a scope (e.g., `repo`, `worktree`, `ctl`) with a scope
507/// field that gets injected into the JSON schema and extracted in the handler to build
508/// the scope chain for `call_scoped_method`.
509fn register_scoped_tools_recursive(
510    reg: &mut ToolRegistry,
511    service_name: &str,
512    nodes: &'static [hyprstream_service::ScopedClientTreeNode],
513    prefix: &str,
514    parent_scopes: &[ScopeInfo],
515) {
516    for node in nodes {
517        let new_prefix = format!("{}.{}", prefix, node.scope_name);
518        let (_, _, methods) = (node.metadata_fn)();
519
520        // Accumulate: parents + this node's (scope_name, field_name, type)
521        let mut scopes: Vec<ScopeInfo> = parent_scopes.to_vec();
522        if !node.scope_field.is_empty() {
523            let field_type = match node.scope_field {
524                "fid" => "UInt32",
525                _ => "Text",
526            };
527            scopes.push((node.scope_name, node.scope_field, field_type));
528        }
529
530        for method in methods {
531            // FIX-7: respect $cliHidden — don't expose internal methods as MCP tools
532            if method.hidden {
533                continue;
534            }
535            let tool_name = format!("{}.{}", new_prefix, method.name);
536
537            // Build JSON schema: method params + all scope fields from ancestors
538            let params: Vec<(&str, &str, bool, &str)> = method
539                .params
540                .iter()
541                .map(|p| (p.name, p.type_name, p.required, p.description))
542                .collect();
543            let mut json_schema = params_to_json_schema(&params);
544            if let Value::Object(ref mut map) = json_schema {
545                let existing_props: Vec<String> = map
546                    .get("properties")
547                    .and_then(|p| p.as_object())
548                    .map(|p| p.keys().cloned().collect())
549                    .unwrap_or_default();
550
551                if let Some(Value::Object(ref mut props)) = map.get_mut("properties") {
552                    for &(_, field_name, field_type) in &scopes {
553                        // Skip scope fields that collide with method params
554                        if existing_props.contains(&field_name.to_owned()) {
555                            continue;
556                        }
557                        let json_type = match field_type {
558                            "UInt8" | "UInt16" | "UInt32" | "UInt64" | "Int8" | "Int16"
559                            | "Int32" | "Int64" => "integer",
560                            "Float32" | "Float64" => "number",
561                            "Bool" => "boolean",
562                            _ => "string",
563                        };
564                        props.insert(
565                            field_name.into(),
566                            serde_json::json!({
567                                "type": json_type,
568                                "description": field_name,
569                            }),
570                        );
571                    }
572                }
573                if let Some(Value::Array(ref mut req)) = map.get_mut("required") {
574                    for (i, &(_, field_name, _)) in scopes.iter().enumerate() {
575                        // Avoid duplicate required entries
576                        let field_str = Value::String(field_name.into());
577                        if !req.contains(&field_str) {
578                            req.insert(i, field_str);
579                        }
580                    }
581                }
582            }
583
584            let method_name = method.name.to_owned();
585            let service = service_name.to_owned();
586            let description = if method.description.is_empty() {
587                format!("{}::{}", new_prefix, method.name)
588            } else {
589                method.description.to_owned()
590            };
591            let required_scope = mcp_policy_scope(method.scope, service_name, &method_name);
592
593            // Capture (scope_name, field_name) pairs for the handler closure
594            let scope_pairs: Vec<(String, String)> = scopes
595                .iter()
596                .map(|&(scope_name, field_name, _)| (scope_name.to_owned(), field_name.to_owned()))
597                .collect();
598
599            if method.is_streaming {
600                // Streaming scoped tool — uses call_scoped_streaming_method with DH key exchange
601                reg.register(ToolEntry {
602                    uuid: Uuid::new_v5(&MCP_NS, tool_name.as_bytes()),
603                    name: tool_name.clone(),
604                    description,
605                    args_schema: json_schema,
606                    required_scope,
607                    streaming: true,
608                    handler: Arc::new(move |ctx| {
609                        let method = method_name.clone();
610                        let service = service.clone();
611                        let scope_pairs = scope_pairs.clone();
612                        Box::pin(async move {
613                            // Build scope chain from args BEFORE moving ctx fields
614                            // Args are already normalized to camelCase by normalize_mcp_args()
615                            let scope_chain: Vec<(String, String)> = scope_pairs
616                                .iter()
617                                .map(|(scope_name, field_name)| {
618                                    let camel_key = snake_to_camel(field_name);
619                                    let val_str = ctx
620                                        .args
621                                        .get(camel_key.as_str())
622                                        .map(|v| match v {
623                                            Value::String(s) => s.clone(),
624                                            Value::Number(n) => n.to_string(),
625                                            _ => v.to_string(),
626                                        })
627                                        .unwrap_or_default();
628                                    (scope_name.clone(), val_str)
629                                })
630                                .collect();
631
632                            let scope_refs: Vec<(&str, &str)> = scope_chain
633                                .iter()
634                                .map(|(s, v)| (s.as_str(), v.as_str()))
635                                .collect();
636
637                            let (client_secret, client_pubkey) =
638                                hyprstream_rpc::generate_ephemeral_keypair();
639                            let client_pubkey_bytes: [u8; 32] = client_pubkey.to_bytes();
640
641                            // #468: the streaming-method client returns the VERIFIED-capnp
642                            // StreamInfo library type directly (no serde_json::Value round-trip).
643                            let stream_info: hyprstream_rpc::stream_info::StreamInfo = match service
644                                .as_str()
645                            {
646                                "registry" => {
647                                    let delegated_bearer = delegated_resource_bearer(&ctx).await?;
648                                    let client = mcp_registry_client(
649                                        &ctx.signing_key,
650                                        delegated_bearer.as_deref(),
651                                    )?;
652                                    client
653                                        .call_scoped_streaming_method(
654                                            &scope_refs,
655                                            &method,
656                                            &ctx.args,
657                                            client_pubkey_bytes,
658                                        )
659                                        .await?
660                                }
661                                "model" => {
662                                    let client =
663                                        mcp_model_client(&ctx.signing_key, ctx.token.as_deref())?;
664                                    client
665                                        .call_scoped_streaming_method(
666                                            &scope_refs,
667                                            &method,
668                                            &ctx.args,
669                                            client_pubkey_bytes,
670                                        )
671                                        .await?
672                                }
673                                _ => anyhow::bail!(
674                                    "No scoped streaming dispatch for service: {service}"
675                                ),
676                            };
677
678                            // #356: single networked reach shape (UDS-only resolves
679                            // to the same-host fast path inside `networked`).
680                            let DecodedStreamReach {
681                                dh_public,
682                                reach,
683                                broadcast_path,
684                                moql_server_identity,
685                            } = decode_stream_reach(stream_info)?;
686                            // #321: derive_client_stream_keys yields the AEAD enc_key.
687                            let (mac_key, enc_key, topic) =
688                                hyprstream_rpc::derive_client_stream_keys(
689                                    &client_secret,
690                                    &client_pubkey_bytes,
691                                    &dh_public,
692                                )?;
693                            // #358: MCP tool stream consumed live → direct-first; selection only reorders advertised reaches.
694                            let qos = hyprstream_rpc::stream_info::StreamOpt::default();
695                            let handle = MoqStreamHandle::networked_with_server_identity(
696                                reach,
697                                &qos,
698                                broadcast_path,
699                                mac_key,
700                                enc_key,
701                                topic,
702                                moql_server_identity,
703                            );
704
705                            Ok(ToolResult::Stream(Box::new(handle)))
706                        })
707                    }),
708                });
709            } else {
710                // Sync scoped tool — uses call_scoped_method
711                reg.register(ToolEntry {
712                    uuid: Uuid::new_v5(&MCP_NS, tool_name.as_bytes()),
713                    name: tool_name.clone(),
714                    description,
715                    args_schema: json_schema,
716                    required_scope,
717                    streaming: false,
718                    handler: Arc::new(move |ctx| {
719                        let method = method_name.clone();
720                        let service = service.clone();
721                        let scope_pairs = scope_pairs.clone();
722                        Box::pin(async move {
723                            // Build scope chain from args: [("repo", repo_id_val), ("worktree", name_val), ...]
724                            // Args are already normalized to camelCase by normalize_mcp_args()
725                            let scope_chain: Vec<(String, String)> = scope_pairs
726                                .iter()
727                                .map(|(scope_name, field_name)| {
728                                    let camel_key = snake_to_camel(field_name);
729                                    let val_str = ctx
730                                        .args
731                                        .get(camel_key.as_str())
732                                        .map(|v| match v {
733                                            Value::String(s) => s.clone(),
734                                            Value::Number(n) => n.to_string(),
735                                            _ => v.to_string(),
736                                        })
737                                        .unwrap_or_default();
738                                    (scope_name.clone(), val_str)
739                                })
740                                .collect();
741
742                            let scope_refs: Vec<(&str, &str)> = scope_chain
743                                .iter()
744                                .map(|(s, v)| (s.as_str(), v.as_str()))
745                                .collect();
746
747                            dispatch_scoped_call(&service, &scope_refs, &method, &ctx).await
748                        })
749                    }),
750                });
751            }
752        }
753
754        // Recurse into nested scopes
755        register_scoped_tools_recursive(reg, service_name, node.nested, &new_prefix, &scopes);
756    }
757}
758
759/// Dispatch a scoped method call to the appropriate service client.
760///
761/// Builds the service-specific client and calls `call_scoped_method` with the
762/// scope chain (e.g., `[("repo", "abc-123"), ("worktree", "main")]`).
763async fn dispatch_scoped_call(
764    service: &str,
765    scopes: &[(&str, &str)],
766    method: &str,
767    ctx: &ToolCallContext,
768) -> anyhow::Result<ToolResult> {
769    let result = match service {
770        "registry" => {
771            let delegated_bearer = delegated_resource_bearer(ctx).await?;
772            let client = mcp_registry_client(&ctx.signing_key, delegated_bearer.as_deref())?;
773            client.call_scoped_method(scopes, method, &ctx.args).await?
774        }
775        "model" => {
776            let client = mcp_model_client(&ctx.signing_key, ctx.token.as_deref())?;
777            client.call_scoped_method(scopes, method, &ctx.args).await?
778        }
779        _ => anyhow::bail!("No scoped dispatch for service: {service}"),
780    };
781    Ok(ToolResult::Sync(result))
782}
783
784fn register_sync_tool(
785    reg: &mut ToolRegistry,
786    tool_name: &str,
787    description: String,
788    json_schema: Value,
789    required_scope: String,
790    service_name: String,
791    method_name: String,
792) {
793    reg.register(ToolEntry {
794        uuid: Uuid::new_v5(&MCP_NS, tool_name.as_bytes()),
795        name: tool_name.to_owned(),
796        description,
797        args_schema: json_schema,
798        required_scope,
799        streaming: false,
800        handler: Arc::new(move |ctx| {
801            let service = service_name.clone();
802            let method = method_name.clone();
803            Box::pin(async move {
804                let result = dispatch_schema_call(&service, &method, &ctx).await?;
805                Ok(ToolResult::Sync(result))
806            })
807        }),
808    });
809}
810
811fn register_streaming_tool(
812    reg: &mut ToolRegistry,
813    tool_name: &str,
814    description: String,
815    json_schema: Value,
816    required_scope: String,
817    service_name: String,
818    method_name: String,
819) {
820    reg.register(ToolEntry {
821        uuid: Uuid::new_v5(&MCP_NS, tool_name.as_bytes()),
822        name: tool_name.to_owned(),
823        description,
824        args_schema: json_schema,
825        required_scope,
826        streaming: true,
827        handler: Arc::new(move |ctx| {
828            let service = service_name.clone();
829            let method = method_name.clone();
830            Box::pin(async move {
831                let (client_secret, client_pubkey) = hyprstream_rpc::generate_ephemeral_keypair();
832                let client_pubkey_bytes: [u8; 32] = client_pubkey.to_bytes();
833
834                // #468: verified-capnp StreamInfo returned directly (no serde_json round-trip).
835                let stream_info: hyprstream_rpc::stream_info::StreamInfo = match service.as_str() {
836                    "registry" => {
837                        let delegated_bearer = delegated_resource_bearer(&ctx).await?;
838                        let client =
839                            mcp_registry_client(&ctx.signing_key, delegated_bearer.as_deref())?;
840                        client
841                            .call_streaming_method(&method, &ctx.args, client_pubkey_bytes)
842                            .await?
843                    }
844                    "model" => {
845                        let client = mcp_model_client(&ctx.signing_key, ctx.token.as_deref())?;
846                        client
847                            .call_streaming_method(&method, &ctx.args, client_pubkey_bytes)
848                            .await?
849                    }
850                    "tui" => {
851                        let client = mcp_tui_client(&ctx.signing_key, ctx.token.as_deref())?;
852                        client
853                            .call_streaming_method(&method, &ctx.args, client_pubkey_bytes)
854                            .await?
855                    }
856                    _ => anyhow::bail!("No streaming support for service: {}", service),
857                };
858
859                // #356: single networked reach shape (UDS-only resolves to the
860                // same-host fast path inside `networked`).
861                let DecodedStreamReach {
862                    dh_public,
863                    reach,
864                    broadcast_path,
865                    moql_server_identity,
866                } = decode_stream_reach(stream_info)?;
867                // #321: derive_client_stream_keys yields the AEAD enc_key.
868                let (mac_key, enc_key, topic) = hyprstream_rpc::derive_client_stream_keys(
869                    &client_secret,
870                    &client_pubkey_bytes,
871                    &dh_public,
872                )?;
873                // #358: MCP tool stream consumed live → direct-first; selection only reorders advertised reaches.
874                let qos = hyprstream_rpc::stream_info::StreamOpt::default();
875                let handle = MoqStreamHandle::networked_with_server_identity(
876                    reach,
877                    &qos,
878                    broadcast_path,
879                    mac_key,
880                    enc_key,
881                    topic,
882                    moql_server_identity,
883                );
884
885                Ok(ToolResult::Stream(Box::new(handle)))
886            })
887        }),
888    });
889}
890
891/// Convert method params to a JSON Schema for tool arguments.
892///
893/// Takes params as (name, type_name, required, description) tuples — works with any generated module's ParamSchema
894/// since they all have the same layout.
895fn params_to_json_schema(params: &[(&str, &str, bool, &str)]) -> Value {
896    let mut properties = serde_json::Map::new();
897    let mut required = Vec::new();
898
899    for &(name, type_name, is_required, description) in params {
900        let json_type = match type_name {
901            "Text" | "Data" => "string",
902            "Bool" => "boolean",
903            "UInt8" | "UInt16" | "UInt32" | "UInt64" | "Int8" | "Int16" | "Int32" | "Int64" => {
904                "integer"
905            }
906            "Float32" | "Float64" => "number",
907            t if t.starts_with("List(") => "array",
908            _ => "string",
909        };
910
911        let mut param_schema = serde_json::Map::new();
912        param_schema.insert("type".to_owned(), Value::String(json_type.to_owned()));
913        if !description.is_empty() {
914            param_schema.insert(
915                "description".to_owned(),
916                Value::String(description.to_owned()),
917            );
918        }
919
920        properties.insert(name.to_owned(), Value::Object(param_schema));
921        if is_required {
922            required.push(Value::String(name.to_owned()));
923        }
924    }
925
926    serde_json::json!({
927        "type": "object",
928        "properties": properties,
929        "required": required,
930    })
931}
932
933/// The transport-resolved shape of a decoded streaming response (#356).
934///
935/// A single networked shape: every producer now advertises its moq reach via the
936/// canonical `StreamInfo.announcedAt` list (or an empty list when UDS-only, which
937/// `connect_moq_reach`/`MoqStreamHandle::networked` resolve to the same-host UDS
938/// fast path from LOCAL config). There is no longer a wire-published UDS path.
939struct DecodedStreamReach {
940    dh_public: [u8; 32],
941    reach: Vec<hyprstream_rpc::stream_info::Destination>,
942    broadcast_path: String,
943    /// Resolver-verified identity of the server that signed this response.
944    moql_server_identity: hyprstream_rpc::stream_info::MoqlServerIdentity,
945}
946
947/// Decode a streaming response into its moq reach (#356).
948///
949/// Takes the VERIFIED-capnp `StreamInfo` library type as returned by the
950/// streaming-method client (decoded + COSE-verified inside `call_streaming`,
951/// `rpc_client.rs`) — NO `serde_json` round-trip (#468) — yielding the
952/// native-capnp `announcedAt` reach list + `broadcastPath`.
953/// Fails closed when the response carries no broadcast path or DH key.
954fn decode_stream_reach(
955    info: hyprstream_rpc::stream_info::StreamInfo,
956) -> anyhow::Result<DecodedStreamReach> {
957    if info.broadcast_path.is_empty() {
958        anyhow::bail!(
959            "missing broadcastPath in streaming response — server did not initialize moq transport"
960        );
961    }
962    if info.dh_public == [0u8; 32] {
963        anyhow::bail!("server did not provide DH public key for streaming");
964    }
965    Ok(DecodedStreamReach {
966        dh_public: info.dh_public,
967        reach: info.announced_at,
968        broadcast_path: info.broadcast_path,
969        moql_server_identity: info.moql_server_identity,
970    })
971}
972
973/// Dispatch a method call to the appropriate generated client.
974async fn dispatch_schema_call(
975    service: &str,
976    method: &str,
977    ctx: &ToolCallContext,
978) -> anyhow::Result<Value> {
979    let signing_key = ctx.signing_key.clone();
980
981    match service {
982        "model" => {
983            let client = mcp_model_client(&signing_key, ctx.token.as_deref())?;
984            client.call_method(method, &ctx.args).await
985        }
986        "registry" => {
987            let delegated_bearer = delegated_resource_bearer(ctx).await?;
988            let client = mcp_registry_client(&signing_key, delegated_bearer.as_deref())?;
989            client.call_method(method, &ctx.args).await
990        }
991        "policy" => ctx.policy_client.call_method(method, &ctx.args).await,
992        "tui" => {
993            let client = mcp_tui_client(&signing_key, ctx.token.as_deref())?;
994            client.call_method(method, &ctx.args).await
995        }
996        "workflow" => {
997            // Delegated-bearer relay path (#989 review). The MCP envelope is
998            // signed by the MCP service key, so a cnf.jwk/cnf.jkt-bound caller
999            // token MUST travel as a delegated bearer (with_delegated_bearer),
1000            // not as a direct bearer on from_provider — direct would bind cnf
1001            // to the relay key and the token would fail verification at
1002            // WorkflowService. WorkflowService's authorize callback relays the
1003            // delegated bearer to PolicyService via check_with_verified_bearer
1004            // (same path as WorkerService), which validates the delegation.
1005            let mut client = WorkflowClient::from_provider(
1006                &hyprstream_discovery::ProductionRpcClientProvider,
1007                signing_key,
1008                None,
1009            )?;
1010            if let Some(bearer) = ctx.token.as_ref() {
1011                client = client.with_delegated_bearer(bearer.clone());
1012            }
1013            client.call_method(method, &ctx.args).await
1014        }
1015        _ => anyhow::bail!("Unknown service: {service}"),
1016    }
1017}
1018
1019// ═══════════════════════════════════════════════════════════════════════════════
1020// McpService
1021// ═══════════════════════════════════════════════════════════════════════════════
1022
1023/// MCP service implementation — UUID-keyed tool registry
1024pub struct McpService {
1025    /// UUID-keyed tool registry (RwLock for live refresh)
1026    registry: Arc<RwLock<ToolRegistry>>,
1027    /// Raw HYPRSTREAM_TOKEN from env (stdio transport — decoded per-request)
1028    stdio_token: Option<String>,
1029    /// Verifying key for JWT validation
1030    verifying_key: VerifyingKey,
1031    // === RequestService infrastructure ===
1032    transport: TransportConfig,
1033    signing_key: SigningKey,
1034    /// ServiceContext for typed_client() / client() access
1035    service_ctx: Option<Arc<ServiceContext>>,
1036    /// Expected audience for tokens (resource URL, for defense-in-depth)
1037    expected_audience: Option<String>,
1038    /// JWT key source for verifying JWTs on ZMQ path (unified local + federated).
1039    jwt_key_source: Option<std::sync::Arc<dyn hyprstream_rpc::auth::JwtKeySource>>,
1040    /// Policy client for authorization checks (shared, avoids per-call socket creation)
1041    policy_client: PolicyClient,
1042}
1043
1044/// Resolve the stdio caller identity from the `HYPRSTREAM_TOKEN` env token.
1045///
1046/// Fail closed (#1095): a token that is *present but fails to decode*
1047/// (expired, malformed, wrong key or audience) is positive evidence of a bad
1048/// credential and is hard-rejected — never silently downgraded to anonymous.
1049/// Only a genuinely absent token routes to the anonymous principal, which
1050/// remains an explicit deployment choice for local stdio use.
1051fn stdio_user(
1052    token: Option<&str>,
1053    verifying_key: &VerifyingKey,
1054    expected_audience: Option<&str>,
1055) -> Result<crate::server::middleware::AuthenticatedUser, ErrorData> {
1056    match token {
1057        Some(token) => jwt::decode(token, verifying_key, expected_audience)
1058            .and_then(|claims| {
1059                let identity = crate::server::middleware::AuthenticatedUser {
1060                    user: claims.sub,
1061                    verified_tenant: claims.tenant,
1062                    token: Some(token.to_owned()),
1063                    exp: Some(claims.exp),
1064                };
1065                identity
1066                    .authorization_domain()
1067                    .map(|_| identity)
1068                    .map_err(|_| jwt::JwtError::InvalidFormat)
1069            })
1070            .map_err(|e| {
1071                warn!(
1072                    "MCP stdio auth: rejecting request, token decode failed ({})",
1073                    e
1074                );
1075                ErrorData::new(
1076                    MCP_AUTH_ERROR,
1077                    format!("MCP stdio authentication failed: {}", e),
1078                    None,
1079                )
1080            }),
1081        None => Err(ErrorData::new(
1082            MCP_AUTH_ERROR,
1083            "MCP stdio authentication failed: verified tenant token required".to_owned(),
1084            None,
1085        )),
1086    }
1087}
1088
1089impl McpService {
1090    /// Create a new McpService with JWT authentication
1091    pub fn new(config: McpConfig) -> anyhow::Result<Self> {
1092        let stdio_token = std::env::var("HYPRSTREAM_TOKEN").ok();
1093
1094        let mut tool_reg = ToolRegistry::new();
1095        register_schema_tools(&mut tool_reg);
1096
1097        tracing::info!(
1098            "McpService registered {} tools (all schema-discovered)",
1099            tool_reg.by_uuid.len(),
1100        );
1101
1102        // Required profile resolves through the checkpoint-backed discovery
1103        // resolver; compatibility dials the factory-resolved deterministic
1104        // IPC transport — registry-free, so a separate rootless Quadlet
1105        // process can reach the PolicyService socket.
1106        // The v2 delegated-bearer exchange calls policy:IssueToken through
1107        // this client. An anonymous envelope presents no authority-asserted
1108        // clearance, so on a MAC-labeled node the exchange dies at the
1109        // policy dispatch PEP with NoClearance and every 9P leaf returns
1110        // -32603. Attach this service's own enrolled credential — the same
1111        // trust-store lookup the registry/model/tui client helpers use — so
1112        // the exchange presents `service:mcp` with its enrolled clearance.
1113        // A deployment that never enrolled the service keeps the anonymous
1114        // envelope: construction must not fail before a ceremony exists.
1115        let policy_credential = mcp_service_token(&config.signing_key).ok();
1116        if policy_credential.is_none() {
1117            warn!(
1118                "MCP policy client has no enrolled service credential; \
1119                 MAC-labeled deployments will deny the delegated-bearer exchange"
1120            );
1121        }
1122        let policy_client = if hyprstream_discovery::native_network_required() {
1123            PolicyClient::from_provider(
1124                &hyprstream_discovery::ProductionRpcClientProvider,
1125                config.signing_key.clone(),
1126                policy_credential,
1127            )?
1128        } else {
1129            PolicyClient::for_local_transport_bootstrap(
1130                &config.policy_transport,
1131                config.signing_key.clone(),
1132                config.policy_verifying_key,
1133                policy_credential,
1134            )?
1135        };
1136
1137        Ok(Self {
1138            registry: Arc::new(RwLock::new(tool_reg)),
1139            stdio_token,
1140            verifying_key: config.verifying_key,
1141            transport: config.transport,
1142            signing_key: config.signing_key,
1143            service_ctx: config.ctx,
1144            expected_audience: config.expected_audience,
1145            jwt_key_source: config.jwt_key_source,
1146            policy_client,
1147        })
1148    }
1149
1150    /// Convert registry to rmcp Tool list (includes built-in refresh_tools meta-tool)
1151    fn tools_list(&self) -> Vec<Tool> {
1152        let reg = self.registry.read();
1153        let mut tools: Vec<Tool> = reg
1154            .list()
1155            .map(|entry| {
1156                let schema: JsonObject = match &entry.args_schema {
1157                    Value::Object(m) => m.clone(),
1158                    _ => JsonObject::new(),
1159                };
1160                Tool {
1161                    name: Cow::Owned(entry.uuid.to_string()),
1162                    title: Some(entry.name.clone()),
1163                    description: Some(Cow::Owned(entry.description.clone())),
1164                    input_schema: Arc::new(schema),
1165                    output_schema: None,
1166                    annotations: Some(ToolAnnotations {
1167                        title: Some(entry.name.clone()),
1168                        read_only_hint: Some(entry.required_scope.starts_with("query:")),
1169                        destructive_hint: Some(!entry.required_scope.starts_with("query:")),
1170                        open_world_hint: Some(false),
1171                        // FIX-8: only query-scoped tools are idempotent; write/train/manage ops are not
1172                        idempotent_hint: Some(entry.required_scope.starts_with("query:")),
1173                    }),
1174                    icons: None,
1175                    meta: None,
1176                }
1177            })
1178            .collect();
1179
1180        let mut refresh_schema = JsonObject::new();
1181        refresh_schema.insert("type".to_owned(), Value::String("object".to_owned()));
1182        tools.push(Tool {
1183            name: Cow::Owned(REFRESH_TOOLS_UUID.to_string()),
1184            title: Some("mcp.refresh_tools".to_owned()),
1185            description: Some(Cow::Borrowed(
1186                "Rebuild the tool registry from current service schemas and notify \
1187                 this session to re-fetch the tool list. Call after new services come \
1188                 online to discover their tools without reconnecting.",
1189            )),
1190            input_schema: Arc::new(refresh_schema),
1191            output_schema: None,
1192            annotations: Some(ToolAnnotations {
1193                title: Some("mcp.refresh_tools".to_owned()),
1194                read_only_hint: Some(false),
1195                destructive_hint: Some(false),
1196                open_world_hint: Some(false),
1197                idempotent_hint: Some(true),
1198            }),
1199            icons: None,
1200            meta: None,
1201        });
1202
1203        tools
1204    }
1205
1206    /// Extract identity from validated middleware state or fall back to env/local.
1207    ///
1208    /// This is pure authentication (identity extraction). No audience checks,
1209    /// no scope filtering — ZMQ backends handle authorization via Casbin.
1210    ///
1211    /// Priority:
1212    /// 1. HTTP transport: use `AuthenticatedUser` from middleware (already validated)
1213    /// 2. Stdio/ZMQ transport (no HTTP Parts): use env var JWT claims or `"anonymous"`
1214    ///
1215    /// Fails closed (#1095): an undecodable stdio token is a hard rejection,
1216    /// never an anonymous downgrade.
1217    fn extract_user(
1218        &self,
1219        context: &RequestContext<RoleServer>,
1220    ) -> Result<crate::server::middleware::AuthenticatedUser, ErrorData> {
1221        if let Some(parts) = context.extensions.get::<http::request::Parts>() {
1222            if let Some(auth_user) = parts
1223                .extensions
1224                .get::<crate::server::middleware::AuthenticatedUser>()
1225            {
1226                trace!(
1227                    "MCP HTTP auth: using validated identity for {}",
1228                    auth_user.user
1229                );
1230                auth_user.authorization_domain().map_err(|_| {
1231                    ErrorData::new(
1232                        MCP_AUTH_ERROR,
1233                        "MCP HTTP authorization failed: verified tenant binding required",
1234                        None,
1235                    )
1236                })?;
1237                return Ok(auth_user.clone());
1238            }
1239
1240            if parts.headers.contains_key(AUTHORIZATION) {
1241                warn!("MCP HTTP auth: Authorization header present but no AuthenticatedUser — middleware should have rejected");
1242            } else {
1243                trace!("MCP HTTP auth: no Authorization header, anonymous access");
1244            }
1245            Err(ErrorData::new(
1246                MCP_AUTH_ERROR,
1247                "MCP HTTP authentication failed: authenticated identity missing",
1248                None,
1249            ))
1250        } else {
1251            trace!("MCP HTTP auth: no http::request::Parts in extensions (stdio/zmq transport)");
1252            stdio_user(
1253                self.stdio_token.as_deref(),
1254                &self.verifying_key,
1255                self.expected_audience.as_deref(),
1256            )
1257        }
1258    }
1259
1260    /// Dispatch a tool call by UUID with a specific identity
1261    async fn dispatch_tool(
1262        &self,
1263        uuid: &Uuid,
1264        args: Value,
1265        identity: crate::server::middleware::AuthenticatedUser,
1266    ) -> Result<CallToolResult, ErrorData> {
1267        let (handler, required_scope) = {
1268            let reg = self.registry.read();
1269            let entry = reg.get(uuid).ok_or_else(|| {
1270                ErrorData::invalid_request(format!("Unknown tool: {}", uuid), None)
1271            })?;
1272            (entry.handler.clone(), entry.required_scope.clone())
1273        };
1274
1275        let domain = identity.authorization_domain().map_err(|_| {
1276            ErrorData::new(
1277                MCP_AUTH_ERROR,
1278                "MCP authorization failed: verified tenant binding required",
1279                None,
1280            )
1281        })?;
1282        let (operation, resource) = required_scope.split_once(':').ok_or_else(|| {
1283            ErrorData::internal_error(
1284                format!("Tool has invalid required scope: {required_scope}"),
1285                None,
1286            )
1287        })?;
1288        let request = PolicyCheck {
1289            subject: identity.user.clone(),
1290            domain: domain.clone(),
1291            resource: resource.to_owned(),
1292            operation: operation.to_owned(),
1293        };
1294        let allowed = crate::services::policy::check_with_verified_bearer(
1295            &self.policy_client,
1296            &request,
1297            identity.token.as_deref(),
1298            &hyprstream_rpc::envelope::Subject::new(identity.user.clone()),
1299        )
1300        .await
1301        .unwrap_or(false);
1302        if !allowed {
1303            tracing::info!(
1304                subject = %identity.user,
1305                %domain,
1306                %resource,
1307                %operation,
1308                "MCP HTTP tool policy denied"
1309            );
1310            return Err(ErrorData::new(
1311                ErrorCode(-32003),
1312                "MCP tool call forbidden by tenant policy",
1313                None,
1314            ));
1315        }
1316
1317        let ctx = ToolCallContext {
1318            args: normalize_mcp_args(args),
1319            signing_key: self.signing_key.clone(),
1320            user: identity.user,
1321            domain,
1322            ctx: self.service_ctx.clone(),
1323            policy_client: self.policy_client.clone(),
1324            // Preserve the verified caller bearer so JWT-backed services
1325            // (e.g. WorkflowService) authorize the actual caller, not an
1326            // anonymous dial (#989 review fix).
1327            token: identity.token,
1328        };
1329
1330        let result = handler(ctx)
1331            .await
1332            .map_err(|e| ErrorData::internal_error(format!("Tool failed: {}", e), None))?;
1333
1334        match result {
1335            ToolResult::Sync(value) => Ok(CallToolResult::success(vec![Content::text(
1336                value.to_string(),
1337            )])),
1338            ToolResult::Stream(mut handle) => {
1339                // Consume StreamHandle — DH, SUB, HMAC all handled internally
1340                let mut contents = Vec::new();
1341                while let Some(payload) = handle
1342                    .recv_next()
1343                    .await
1344                    .map_err(|e| ErrorData::internal_error(format!("Stream error: {}", e), None))?
1345                {
1346                    match payload {
1347                        StreamPayload::Data(data) => {
1348                            contents
1349                                .push(Content::text(String::from_utf8_lossy(&data).to_string()));
1350                        }
1351                        StreamPayload::Complete(meta) => {
1352                            contents
1353                                .push(Content::text(String::from_utf8_lossy(&meta).to_string()));
1354                            break;
1355                        }
1356                        StreamPayload::Error(msg) => {
1357                            return Err(ErrorData::internal_error(msg, None));
1358                        }
1359                        StreamPayload::Tagged { .. } => {
1360                            // encrypted event payload, skip
1361                        }
1362                    }
1363                }
1364                Ok(CallToolResult::success(contents))
1365            }
1366        }
1367    }
1368}
1369
1370// ═══════════════════════════════════════════════════════════════════════════════
1371// ServerHandler Implementation (manual — no macros)
1372// ═══════════════════════════════════════════════════════════════════════════════
1373
1374impl ServerHandler for McpService {
1375    fn get_info(&self) -> ServerInfo {
1376        ServerInfo {
1377            protocol_version: Default::default(),
1378            capabilities: ServerCapabilities::builder()
1379                .enable_tools()
1380                .enable_tool_list_changed()
1381                .build(),
1382            server_info: rmcp::model::Implementation {
1383                name: "hyprstream".into(),
1384                version: env!("CARGO_PKG_VERSION").into(),
1385                icons: None,
1386                title: None,
1387                website_url: None,
1388            },
1389            instructions: Some(
1390                "Hyprstream AI inference service. \
1391                 Connect via HTTP transport (url-based) for automatic OAuth authentication. \
1392                 For stdio transport, set HYPRSTREAM_TOKEN env var if needed."
1393                    .into(),
1394            ),
1395        }
1396    }
1397
1398    fn list_tools(
1399        &self,
1400        _request: Option<PaginatedRequestParams>,
1401        _context: RequestContext<RoleServer>,
1402    ) -> impl std::future::Future<Output = Result<ListToolsResult, ErrorData>> + Send + '_ {
1403        // Tool listing is public; authorization happens at call_tool time via ZMQ backends
1404        std::future::ready(Ok(ListToolsResult {
1405            meta: None,
1406            tools: self.tools_list(),
1407            next_cursor: None,
1408        }))
1409    }
1410
1411    fn call_tool(
1412        &self,
1413        request: CallToolRequestParams,
1414        context: RequestContext<RoleServer>,
1415    ) -> impl std::future::Future<Output = Result<CallToolResult, ErrorData>> + Send + '_ {
1416        let user = self.extract_user(&context);
1417        async move {
1418            // Fail closed: reject before dispatch when authentication failed (#1095)
1419            let user = user?;
1420            let uuid = Uuid::parse_str(&request.name)
1421                .map_err(|e| ErrorData::invalid_request(format!("Invalid UUID: {}", e), None))?;
1422
1423            if uuid == REFRESH_TOOLS_UUID {
1424                let old_count;
1425                let new_count;
1426                {
1427                    let mut reg = self.registry.write();
1428                    old_count = reg.by_uuid.len();
1429                    let mut fresh = ToolRegistry::new();
1430                    register_schema_tools(&mut fresh);
1431                    new_count = fresh.by_uuid.len();
1432                    *reg = fresh;
1433                }
1434                let _ = context.peer.notify_tool_list_changed().await;
1435                tracing::info!("MCP refresh_tools: {} -> {} tools", old_count, new_count);
1436                return Ok(CallToolResult::success(vec![Content::text(format!(
1437                    "Refreshed tool registry: {} tools (was {})",
1438                    new_count, old_count
1439                ))]));
1440            }
1441
1442            let args = match request.arguments {
1443                Some(map) => Value::Object(map),
1444                None => Value::Object(serde_json::Map::new()),
1445            };
1446
1447            self.dispatch_tool(&uuid, args, user).await
1448        }
1449    }
1450}
1451
1452// ═══════════════════════════════════════════════════════════════════════════════
1453// McpHandler Implementation (generated trait)
1454// ═══════════════════════════════════════════════════════════════════════════════
1455
1456#[async_trait::async_trait(?Send)]
1457impl McpHandler for McpService {
1458    async fn authorize(
1459        &self,
1460        ctx: &crate::services::EnvelopeContext,
1461        resource: &str,
1462        operation: &str,
1463    ) -> anyhow::Result<()> {
1464        let subject = ctx.subject().to_string();
1465        let domain = ctx.domain()?;
1466        let request = PolicyCheck {
1467            subject: subject.clone(),
1468            domain,
1469            resource: resource.to_owned(),
1470            operation: operation.to_owned(),
1471        };
1472        let result = crate::services::policy::check_with_holder_evidence(
1473            &self.policy_client,
1474            &request,
1475            ctx.jwt_token(),
1476            &ctx.subject(),
1477            ctx.original_holder_evidence(),
1478        )
1479        .await;
1480        match result {
1481            Ok(allowed) => {
1482                if allowed {
1483                    Ok(())
1484                } else {
1485                    tracing::info!(
1486                        "MCP policy denied: sub={} obj={} act={}",
1487                        subject,
1488                        resource,
1489                        operation
1490                    );
1491                    anyhow::bail!(
1492                        "Unauthorized: {} cannot {} on {}",
1493                        subject,
1494                        operation,
1495                        resource
1496                    )
1497                }
1498            }
1499            Err(e) => {
1500                tracing::warn!(
1501                    "MCP policy check RPC error: sub={} obj={} act={} err={}",
1502                    subject,
1503                    resource,
1504                    operation,
1505                    e
1506                );
1507                anyhow::bail!(
1508                    "Unauthorized: {} cannot {} on {} (policy check error: {})",
1509                    subject,
1510                    operation,
1511                    resource,
1512                    e
1513                )
1514            }
1515        }
1516    }
1517
1518    async fn handle_get_status(
1519        &self,
1520        _ctx: &crate::services::EnvelopeContext,
1521        _request_id: u64,
1522    ) -> anyhow::Result<McpResponseVariant> {
1523        let loaded_model_count = {
1524            // Status check uses local identity (internal health check, no user context)
1525            let client = mcp_model_client(&self.signing_key, None)?;
1526            client
1527                .status(&hyprstream_rpc_std::model_client::StatusRequest {
1528                    model_ref: String::new(),
1529                })
1530                .await
1531                .map(|models| models.len() as u32)
1532                .unwrap_or(0)
1533        };
1534
1535        Ok(McpResponseVariant::GetStatusResult(ServiceStatus {
1536            is_running: true,
1537            loaded_model_count,
1538            is_authenticated: self.stdio_token.is_some(),
1539            authenticated_user: self
1540                .stdio_token
1541                .as_ref()
1542                .and_then(|t| {
1543                    jwt::decode(t, &self.verifying_key, self.expected_audience.as_deref()).ok()
1544                })
1545                .map(|c| c.sub)
1546                .unwrap_or_default(),
1547            scopes: vec![], // Scopes no longer in JWT; authorization via Casbin
1548        }))
1549    }
1550
1551    async fn handle_list_tools(
1552        &self,
1553        _ctx: &crate::services::EnvelopeContext,
1554        _request_id: u64,
1555    ) -> anyhow::Result<McpResponseVariant> {
1556        let reg = self.registry.read();
1557        let tools: Vec<ToolDefinition> = reg
1558            .list()
1559            .map(|entry| ToolDefinition {
1560                name: entry.uuid.to_string(),
1561                description: entry.description.clone(),
1562                is_read_only: entry.required_scope.starts_with("query:"),
1563                is_destructive: !entry.required_scope.starts_with("query:"),
1564                required_scope: entry.required_scope.clone(),
1565                argument_schema: entry.args_schema.to_string(),
1566            })
1567            .collect();
1568
1569        Ok(McpResponseVariant::ListToolsResult(ToolList { tools }))
1570    }
1571
1572    async fn handle_get_metrics(
1573        &self,
1574        _ctx: &crate::services::EnvelopeContext,
1575        _request_id: u64,
1576    ) -> anyhow::Result<McpResponseVariant> {
1577        Ok(McpResponseVariant::GetMetricsResult(ServiceMetrics {
1578            total_calls: 0,
1579            calls_per_tool: Vec::new(),
1580            average_call_duration_ms: 0.0,
1581            uptime_seconds: 0.0,
1582        }))
1583    }
1584
1585    async fn handle_call_tool(
1586        &self,
1587        ctx: &crate::services::EnvelopeContext,
1588        _request_id: u64,
1589        data: &CallTool,
1590    ) -> anyhow::Result<McpResponseVariant> {
1591        let uuid = Uuid::parse_str(&data.tool_name)
1592            .map_err(|e| anyhow::anyhow!("Invalid tool UUID '{}': {}", data.tool_name, e))?;
1593
1594        let args: Value = if data.arguments.is_empty() {
1595            Value::Object(serde_json::Map::new())
1596        } else {
1597            serde_json::from_str(&data.arguments)?
1598        };
1599
1600        let identity = crate::server::middleware::AuthenticatedUser {
1601            user: ctx.subject().to_string(),
1602            verified_tenant: ctx.verified_tenant().map(str::to_owned),
1603            token: None,
1604            exp: None,
1605        };
1606        let result = self.dispatch_tool(&uuid, args, identity).await;
1607
1608        match result {
1609            Ok(call_result) => {
1610                use rmcp::model::RawContent;
1611                let text: String = call_result
1612                    .content
1613                    .iter()
1614                    .filter_map(|c| match &c.raw {
1615                        RawContent::Text(t) => Some(t.text.as_str()),
1616                        _ => None,
1617                    })
1618                    .collect::<Vec<_>>()
1619                    .join("");
1620                Ok(McpResponseVariant::CallToolResult(
1621                    hyprstream_rpc_std::mcp_client::ToolResult {
1622                        success: true,
1623                        result: text,
1624                        error_message: String::new(),
1625                    },
1626                ))
1627            }
1628            Err(e) => Ok(McpResponseVariant::CallToolResult(
1629                hyprstream_rpc_std::mcp_client::ToolResult {
1630                    success: false,
1631                    result: "null".to_owned(),
1632                    error_message: format!("{}", e),
1633                },
1634            )),
1635        }
1636    }
1637}
1638
1639// ═══════════════════════════════════════════════════════════════════════════════
1640// RequestService Implementation (internal control plane)
1641// ═══════════════════════════════════════════════════════════════════════════════
1642
1643#[async_trait(?Send)]
1644impl RequestService for McpService {
1645    fn decode_request_body(
1646        &self,
1647        signed_body: &[u8],
1648    ) -> anyhow::Result<hyprstream_rpc::service::DecodedRequestBody> {
1649        // The ONE bounded decode (v16 §5.2): the generated decoder derives
1650        // the full method leaf and returns the decoded message that policy,
1651        // MAC, and dispatch below all consume.
1652        crate::services::generated::mcp_client::decode_mcp_request_body(signed_body)
1653    }
1654
1655    async fn handle_request(
1656        &self,
1657        ctx: &crate::services::EnvelopeContext,
1658        body: &hyprstream_rpc::service::DecodedRequestBody,
1659    ) -> anyhow::Result<(Vec<u8>, Option<crate::services::Continuation>)> {
1660        trace!(
1661            "McpService request from {} (id={})",
1662            ctx.subject(),
1663            ctx.request_id
1664        );
1665        dispatch_mcp(self, ctx, body).await
1666    }
1667
1668    fn name(&self) -> &str {
1669        "mcp"
1670    }
1671
1672    fn transport(&self) -> &TransportConfig {
1673        &self.transport
1674    }
1675
1676    fn signing_key(&self) -> SigningKey {
1677        self.signing_key.clone()
1678    }
1679
1680    fn expected_audience(&self) -> Option<&str> {
1681        self.expected_audience.as_deref()
1682    }
1683
1684    fn jwt_key_source(&self) -> Option<std::sync::Arc<dyn hyprstream_rpc::auth::JwtKeySource>> {
1685        self.jwt_key_source.clone()
1686    }
1687
1688    fn build_error_payload(&self, request_id: u64, error: &str) -> Vec<u8> {
1689        let variant = McpResponseVariant::Error(ErrorInfo {
1690            message: error.to_owned(),
1691            code: "INTERNAL".to_owned(),
1692            details: String::new(),
1693        });
1694        serialize_response(request_id, &variant).unwrap_or_default()
1695    }
1696}
1697
1698// ═══════════════════════════════════════════════════════════════════════════════
1699// Tests
1700// ═══════════════════════════════════════════════════════════════════════════════
1701
1702#[cfg(test)]
1703#[allow(clippy::unwrap_used, clippy::expect_used)]
1704mod tests {
1705    use super::*;
1706    use hyprstream_rpc::auth::Claims;
1707
1708    fn signing_key(seed: u8) -> SigningKey {
1709        SigningKey::from_bytes(&[seed; 32])
1710    }
1711
1712    /// MCP must be constructible before any in-process endpoint registry has
1713    /// been populated: rootless Quadlets reach Policy through the shared IPC
1714    /// socket selected by the factory.
1715    #[test]
1716    fn mcp_accepts_unregistered_ipc_policy_transport() {
1717        let signing_key = signing_key(0x51);
1718        let config = McpConfig {
1719            verifying_key: signing_key.verifying_key(),
1720            signing_key: signing_key.clone(),
1721            transport: TransportConfig::ipc("/run/hyprstream/mcp.sock"),
1722            policy_transport: TransportConfig::ipc("/run/hyprstream/policy.sock"),
1723            ctx: None,
1724            policy_verifying_key: signing_key.verifying_key(),
1725            expected_audience: None,
1726            jwt_key_source: None,
1727        };
1728
1729        assert!(McpService::new(config).is_ok());
1730    }
1731
1732    #[test]
1733    fn entire_tool_catalog_has_object_input_schemas() {
1734        let signing_key = signing_key(0x52);
1735        let service = McpService::new(McpConfig {
1736            verifying_key: signing_key.verifying_key(),
1737            signing_key: signing_key.clone(),
1738            transport: TransportConfig::ipc("/run/hyprstream/mcp.sock"),
1739            policy_transport: TransportConfig::ipc("/run/hyprstream/policy.sock"),
1740            ctx: None,
1741            policy_verifying_key: signing_key.verifying_key(),
1742            expected_audience: None,
1743            jwt_key_source: None,
1744        })
1745        .expect("construct MCP service");
1746        let tools = service.tools_list();
1747        assert!(!tools.is_empty());
1748        assert!(tools
1749            .iter()
1750            .any(|tool| tool.name.as_ref() == REFRESH_TOOLS_UUID.to_string()));
1751        for tool in tools {
1752            let wire = serde_json::to_value(&tool).expect("serialize MCP tool");
1753            assert_eq!(
1754                wire["inputSchema"]["type"], "object",
1755                "invalid input schema for {}",
1756                tool.name
1757            );
1758        }
1759    }
1760
1761    #[test]
1762    fn mcp_internal_clients_fail_closed_without_a_nonempty_service_token() {
1763        assert!(nonempty_mcp_service_token(None).is_err());
1764        assert!(nonempty_mcp_service_token(Some(" \t".to_owned())).is_err());
1765        assert_eq!(
1766            nonempty_mcp_service_token(Some("bound-service-token".to_owned()))
1767                .expect("nonempty service token"),
1768            "bound-service-token"
1769        );
1770        assert!(delegated_mcp_bearer(Some("\n")).is_err());
1771        assert_eq!(
1772            delegated_mcp_bearer(Some("verified-user-token")).expect("nonblank delegated token"),
1773            Some("verified-user-token".to_owned())
1774        );
1775    }
1776
1777    #[test]
1778    fn delegated_bearer_ttl_is_clamped_to_five_minutes() {
1779        let now = 1_800_000_000;
1780        assert_eq!(
1781            delegated_bearer_ttl(now + 3600, now).expect("fresh token"),
1782            300
1783        );
1784    }
1785
1786    #[test]
1787    fn delegated_bearer_ttl_uses_remaining_lifetime_when_shorter() {
1788        let now = 1_800_000_000;
1789        assert_eq!(
1790            delegated_bearer_ttl(now + 120, now).expect("fresh token"),
1791            120
1792        );
1793    }
1794
1795    #[test]
1796    fn delegated_bearer_ttl_fails_closed_on_expired_caller_token() {
1797        let now = 1_800_000_000;
1798        assert!(delegated_bearer_ttl(now, now).is_err());
1799        assert!(delegated_bearer_ttl(now - 1, now).is_err());
1800    }
1801
1802    #[test]
1803    fn registry_model_and_tui_mcp_dispatch_use_the_authenticated_client_helpers() {
1804        let source = include_str!("mcp_service.rs");
1805        let production = source
1806            .split("// Tests")
1807            .next()
1808            .expect("tests banner bounds production source");
1809        for tokenless_client in [
1810            "RegistryClient::from_provider(&hyprstream_discovery::ProductionRpcClientProvider, ctx.signing_key, None)",
1811            "ModelClient::from_provider(&hyprstream_discovery::ProductionRpcClientProvider, ctx.signing_key, None)",
1812            "TuiClient::from_provider(&hyprstream_discovery::ProductionRpcClientProvider, ctx.signing_key, None)",
1813        ] {
1814            assert!(
1815                !production.contains(tokenless_client),
1816                "MCP production dispatch must not construct {tokenless_client}"
1817            );
1818        }
1819        assert!(production
1820            .contains("mcp_registry_client(&ctx.signing_key, delegated_bearer.as_deref())"));
1821        assert!(production.contains("mcp_model_client(&ctx.signing_key, ctx.token.as_deref())"));
1822        assert!(production.contains("mcp_tui_client(&ctx.signing_key, ctx.token.as_deref())"));
1823    }
1824
1825    /// The v2 delegated-bearer exchange mints through the MCP→Policy client,
1826    /// so that client must present the service's own enrolled credential —
1827    /// an anonymous envelope is denied NoClearance at the policy MAC
1828    /// dispatch PEP on a labeled node (rehearsal-proven 2026-11-14). Pins
1829    /// the construction structurally, in this file's established style.
1830    #[test]
1831    fn mcp_policy_client_presents_the_enrolled_service_credential() {
1832        let source = include_str!("mcp_service.rs");
1833        let production = source
1834            .split("// Tests")
1835            .next()
1836            .expect("tests banner bounds production source");
1837        assert!(production.contains("mcp_service_token(&config.signing_key).ok()"));
1838        for tokenless in [
1839            "PolicyClient::from_provider(
1840                &hyprstream_discovery::ProductionRpcClientProvider,
1841                config.signing_key.clone(),
1842                None,",
1843            "PolicyClient::for_local_transport_bootstrap(
1844                &config.policy_transport,
1845                config.signing_key.clone(),
1846                config.policy_verifying_key,
1847                None,",
1848        ] {
1849            assert!(
1850                !production.contains(tokenless),
1851                "MCP policy client must not be constructed without a credential: {tokenless:?}"
1852            );
1853        }
1854    }
1855
1856    /// #989: workflow tools must be advertised to MCP clients. Proves both that
1857    /// `register_schema_tools` walks `workflow_client::schema_metadata()` AND
1858    /// that the schema/metadata are wired (a missing registration would leave
1859    /// `workflow.list`/`workflow.dispatch`/… invisible to MCP).
1860    #[test]
1861    fn workflow_tools_registered_for_mcp() {
1862        let mut reg = ToolRegistry::new();
1863        register_schema_tools(&mut reg);
1864        let has_workflow = reg.list().any(|t| t.name.starts_with("workflow."));
1865        assert!(
1866            has_workflow,
1867            "MCP tool registry must expose workflow.* tools (#989)"
1868        );
1869    }
1870
1871    /// #989 review (1194b0d55 follow-up): the workflow dispatch arm must relay a
1872    /// cnf.jwk/cnf.jkt-bound caller token via the **delegated-bearer** path
1873    /// (`with_delegated_bearer`), not as a direct bearer on `from_provider`. The
1874    /// MCP envelope is signed by the MCP service key; a direct bearer would bind
1875    /// `cnf` to the relay key and the token would fail at WorkflowService.
1876    ///
1877    /// The production provider is deployment-owned, so an isolated unit test
1878    /// pins the dispatch arm's bearer semantics structurally over its source
1879    /// text. Full runtime validation (token reaches
1880    /// `WorkflowService::authorize` via a live resolver + PolicyService)
1881    /// remains CI/integration-test scope.
1882    #[test]
1883    fn workflow_dispatch_uses_delegated_bearer_relay_path() {
1884        let source = include_str!("mcp_service.rs");
1885        let production = source
1886            .split("// Tests")
1887            .next()
1888            .expect("'// Tests' banner marker must exist to bound the production text");
1889
1890        let arm_start = production
1891            .find("\"workflow\" => {")
1892            .expect("dispatch_schema_call must have a \"workflow\" match arm");
1893        let arm_end = production[arm_start..]
1894            .find("_ => anyhow::bail!(\"Unknown service: {service}\")")
1895            .expect("the workflow arm must be followed by the catch-all match arm");
1896        // The production source is intentionally checked structurally here,
1897        // so make the assertions insensitive to rustfmt's line wrapping.
1898        let workflow_arm = production[arm_start..arm_start + arm_end]
1899            .split_whitespace()
1900            .collect::<String>();
1901
1902        assert!(
1903            workflow_arm.contains("WorkflowClient::from_provider(&hyprstream_discovery::ProductionRpcClientProvider,signing_key,None,)?;"),
1904            "workflow arm must dial with the explicit provider — no direct bearer"
1905        );
1906        assert!(
1907            workflow_arm.contains("ifletSome(bearer)=ctx.token.as_ref()"),
1908            "workflow arm must branch on the caller's verified token"
1909        );
1910        assert!(
1911            workflow_arm.contains("client=client.with_delegated_bearer(bearer.clone());"),
1912            "workflow arm must relay the caller token via with_delegated_bearer, not a direct bearer"
1913        );
1914        assert!(
1915            !workflow_arm.contains("from_provider(&hyprstream_discovery::ProductionRpcClientProvider, signing_key, Some"),
1916            "workflow arm must NOT pass the caller token as a direct bearer on from_provider — \
1917             a cnf.jwk/cnf.jkt-bound caller token would fail verification at WorkflowService"
1918        );
1919    }
1920
1921    #[test]
1922    fn schema_action_expands_to_tenant_policy_resource() {
1923        assert_eq!(
1924            mcp_policy_scope("query", "registry", "list"),
1925            "query:registry:List"
1926        );
1927        assert_eq!(
1928            mcp_policy_scope("write", "model", "load_model"),
1929            "write:model:LoadModel"
1930        );
1931        assert_eq!(
1932            mcp_policy_scope("", "tui", "health_check"),
1933            "query:tui:HealthCheck"
1934        );
1935    }
1936
1937    /// No token cannot establish a tenant and therefore fails closed.
1938    #[test]
1939    fn stdio_absent_token_is_rejected() {
1940        let vk = signing_key(0x01).verifying_key();
1941        assert!(stdio_user(None, &vk, None).is_err());
1942    }
1943
1944    /// A present, decodable token yields its subject and verified tenant.
1945    #[test]
1946    fn stdio_valid_token_yields_subject() {
1947        let sk = signing_key(0x02);
1948        let token = jwt::encode(
1949            &Claims::new("alice".to_owned(), 0, 9_999_999_999)
1950                .with_tenant("tenant-a.example".to_owned()),
1951            &sk,
1952        );
1953        let user = stdio_user(Some(&token), &sk.verifying_key(), None).unwrap();
1954        assert_eq!(user.user, "alice");
1955        assert_eq!(user.authorization_domain().unwrap(), "tenant-a.example");
1956    }
1957
1958    /// #1095: a present-but-undecodable token must hard-reject (fail closed),
1959    /// never downgrade to anonymous.
1960    #[test]
1961    fn stdio_undecodable_token_is_rejected_not_anonymous() {
1962        let service = signing_key(0x04);
1963        let vk = service.verifying_key();
1964        let expected_aud = Some("https://hyprstream.local");
1965
1966        // Expired (valid signature, past exp)
1967        let expired = jwt::encode(&Claims::new("bob".to_owned(), 0, 1), &service);
1968        // Signed by a foreign key
1969        let wrong_key = jwt::encode(
1970            &Claims::new("carol".to_owned(), 0, 9_999_999_999),
1971            &signing_key(0x05),
1972        );
1973        // Malformed
1974        let malformed = "not-a-jwt".to_owned();
1975        // Wrong audience (valid signature, aud for a different resource)
1976        let wrong_aud = jwt::encode(
1977            &Claims::new("dave".to_owned(), 0, 9_999_999_999)
1978                .with_audience(Some("https://other".to_owned())),
1979            &service,
1980        );
1981
1982        for token in [&expired, &wrong_key, &malformed, &wrong_aud] {
1983            let err = stdio_user(Some(token), &vk, expected_aud)
1984                .expect_err("present-but-undecodable token must be rejected");
1985            assert_eq!(err.code, MCP_AUTH_ERROR, "token: {token}");
1986        }
1987    }
1988
1989    /// A token decodable under the service key and audience is accepted even
1990    /// when another rejection case exists for different parameters.
1991    #[test]
1992    fn stdio_valid_token_with_audience_is_accepted() {
1993        let sk = signing_key(0x06);
1994        let token = jwt::encode(
1995            &Claims::new("erin".to_owned(), 0, 9_999_999_999)
1996                .with_tenant("tenant-a.example".to_owned())
1997                .with_audience(Some("https://hyprstream.local".to_owned())),
1998            &sk,
1999        );
2000        let user = stdio_user(
2001            Some(&token),
2002            &sk.verifying_key(),
2003            Some("https://hyprstream.local"),
2004        )
2005        .unwrap();
2006        assert_eq!(user.user, "erin");
2007    }
2008}