Repository navigation
Expand file tree
/
Copy pathmcp.rs
More file actions
1691 lines (1640 loc) · 62.8 KB
/
Copy pathmcp.rs
File metadata and controls
1691 lines (1640 loc) · 62.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
mod app_registry;
mod cli;
#[cfg(test)]
pub(crate) use cli::parse_call_line_for_test;
mod discovery;
mod execution_control;
mod http_metadata;
mod presentation;
mod protocol;
mod request_policy;
mod resources;
mod response;
pub(crate) mod tool_exposure;
mod tools;
mod workbench;
#[cfg(test)]
pub(crate) use tools::adaptive_runtime_gateway_input_schema_for_test;
use crate::action_audit::{ActionAudit, ActionAuditRecord};
use crate::auth::AuthContext;
use crate::json_error;
use crate::json_measurement::serialized_json_len;
use crate::tool_request_trace::{
estimate_json_bytes, jsonrpc_id_safe, new_trace_id, scope_active_trace,
RequestCompletionTiming, ToolRequestLifecycle,
};
use crate::tool_runtime::kernel::HostFileImportTrust;
use crate::tool_runtime::model_ergonomics_telemetry::{
ModelErgonomicsRecord, ModelErgonomicsTimer,
};
#[cfg(test)]
use crate::tool_runtime::registered_tool_specs;
#[cfg(test)]
use crate::tool_runtime::ToolResult;
use crate::tool_runtime::ToolRuntime;
#[cfg(test)]
use crate::tool_runtime::MAX_PROJECT_ARTIFACT_BYTES;
#[cfg(test)]
use crate::tool_runtime::{
validate_project_artifact_export_snapshot, ProjectArtifactExportSnapshot,
INTERNAL_ARTIFACT_TRANSFER_CHUNK_BYTES, MAX_PROJECT_ARTIFACT_EXPORT_BYTES,
};
#[cfg(test)]
use base64::Engine as _;
use futures_util::stream;
use http_metadata::{request_header, validate_http_protocol, MCP_PROTOCOL_VERSION_HEADER};
#[cfg(test)]
use http_metadata::{
MCP_HEADER_MISMATCH, MCP_METHOD_HEADER, MCP_NAME_HEADER, MCP_UNSUPPORTED_PROTOCOL_VERSION,
};
#[cfg(test)]
use protocol::{
inferred_protocol_era, request_protocol_version, MCP_CHATGPT_PROTOCOL_VERSION,
MCP_SUPPORTED_PROTOCOL_VERSIONS,
};
use protocol::{
JsonRpcRequest, McpProtocolEra, MCP_INFO_METHODS, MCP_PROTOCOL_VERSION,
MCP_STATELESS_PROTOCOL_VERSION,
};
use response::{rpc_error, rpc_result};
use salvo::prelude::*;
use serde_json::{json, Value};
use std::sync::Arc;
#[cfg(test)]
use std::time::{Duration, Instant};
#[cfg(test)]
use tokio::sync::Semaphore;
#[cfg(test)]
use app_registry::*;
#[cfg(test)]
use resources::*;
#[cfg(test)]
use tools::{
add_stateless_workflow_recorder_metadata, mcp_host_file_import_trust_decision_from_state,
mcp_host_file_import_trust_from_state, mcp_tools_list_payload_with_compact,
mcp_tools_list_payload_with_compact_and_app, mcp_tools_list_payload_with_features_for_auth,
parse_mcp_invocation_envelope, take_last_mcp_host_file_import_trust_decision,
HostFileImportTrustReason, McpToolCallParams,
};
/// Hard upper bound on a single MCP JSON-RPC dispatch, applied in `mcp_post`.
///
/// Chosen above every per-tool wait (sync agent waits are clamped to
/// `wait_timeout_secs <= 120` plus a few seconds of margin), so it can only
/// fire when a dispatch path hangs without its own bound. Its job is to turn
/// an otherwise-permanently-silent HTTP request into an explicit JSON-RPC
/// error the client can surface.
const MCP_DISPATCH_HARD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(150);
fn runtime(depot: &Depot) -> Option<Arc<ToolRuntime>> {
depot.obtain::<Arc<ToolRuntime>>().ok().cloned()
}
// Retain only the exact Goal selector for successful Goal Plan polls. This is
// observation correlation, not client liveness evidence or authority. No other
// arguments, Goal body, or Host binding are copied into the activity ledger.
fn goal_plan_observation_id(tool_name: Option<&str>, params: &Value) -> Option<String> {
if tool_name != Some("sync_goal_plan") {
return None;
}
let id = params.pointer("/arguments/goal_id")?.as_str()?;
let suffix = id.strip_prefix("wc_goal_")?;
(suffix.len() == 16
&& suffix
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')))
.then(|| id.to_string())
}
fn work_result_app_internal_tool(tool_name: Option<&str>) -> bool {
matches!(
tool_name,
Some(
"search_mentions"
| "open_webcodex_workbench"
| "search_webcodex_resources"
| "read_webcodex_resource"
| "list_sessions"
| "present_work_result"
| "work_result_thread_panel"
| "get_work_result_state"
| "read_work_result_activity_detail"
| "send_work_result_message"
| "read_changed_file_diff"
)
)
}
fn finalize_mcp_tool_observability(
trace: &ToolRequestLifecycle,
runtime: &ToolRuntime,
audit: Option<&ActionAudit>,
audit_event: Option<(
ActionAuditRecord,
crate::action_audit::ActionAuditRecordTiming,
)>,
model_ergonomics: Option<&ModelErgonomicsRecord>,
live_window_request: &mut Option<crate::tool_runtime::WindowActivityGuard>,
timing: RequestCompletionTiming,
streaming: bool,
continuity_eligible: bool,
outcome_class: &'static str,
) {
let finalize_started = std::time::Instant::now();
let transition = live_window_request
.as_ref()
.map(crate::tool_runtime::WindowActivityGuard::transition);
let meaningful = audit_event
.as_ref()
.is_some_and(|(event, _)| event.window_meaningful);
if let Some(record) = model_ergonomics {
if let Some(target) = live_window_request
.as_ref()
.and_then(|active| active.instruction_read_after_complete_bootstrap(record))
{
crate::tool_runtime::runtime_metrics::observe_instruction_read_after_complete_bootstrap(
runtime.metrics.as_ref(),
target,
);
}
crate::tool_runtime::runtime_metrics::observe_tool_call(runtime.metrics.as_ref(), record);
}
if audit_event.is_some() {
crate::tool_runtime::runtime_metrics::observe_mcp_call(
runtime.metrics.as_ref(),
crate::tool_runtime::runtime_metrics::McpCallMetricObservation {
elapsed_ms: timing.elapsed_ms,
outcome_class,
meaningful,
streaming,
},
);
if meaningful {
if let Some(transition) = transition {
crate::tool_runtime::runtime_metrics::observe_window_transition(
runtime.metrics.as_ref(),
transition,
);
}
}
}
// Keep the request active until its completed observation is durable. A
// detector must never see neither the active call nor its completed work.
let evidence_recorded =
if let (Some(audit), Some((mut event, audit_timing))) = (audit, audit_event) {
if let Some(previous) = live_window_request
.as_ref()
.and_then(|guard| guard.previous_meaningful_call())
{
event.summary["previous_meaningful_call"] = json!(previous);
}
audit.record_with_completion(
event,
audit_timing,
timing,
transition,
streaming,
continuity_eligible,
)
} else {
false
};
if let Some(active) = live_window_request.take() {
active.complete(timing, continuity_eligible, evidence_recorded);
}
crate::tool_request_trace::record_phase_latency_for(
Some(&trace.correlation_trace_id()),
"request_finalize",
finalize_started,
"completed",
);
}
#[cfg(test)]
pub(crate) fn mcp_runtime_tool_result(
tool_name: &str,
as_image_requested: bool,
result: ToolResult,
) -> Value {
tools::mcp_runtime_tool_result(tool_name, as_image_requested, result)
}
/// Outcome of handling a single MCP JSON-RPC request.
///
/// Carries the JSON-RPC response body alongside the HTTP status the HTTP
/// wrapper should render. Keeping this separate from `Response` makes the
/// core protocol logic testable without a live server.
#[derive(Debug)]
enum McpOutcome {
/// A normal JSON-RPC result. HTTP 200 with the body.
Ok(Value),
/// A preflighted artifact resource read whose JSON-RPC body is emitted
/// incrementally by the HTTP wrapper without whole-file aggregation.
ArtifactExportStream {
id: Value,
plan: resources::McpArtifactExportStreamPlan,
},
/// A JSON-RPC protocol error. HTTP 400 with the error body.
BadRequest(Value),
/// A modern MCP method is not implemented. HTTP 404 with JSON-RPC -32601.
NotFound(Value),
/// A JSON-RPC notification (request without an `id` member). Per the
/// JSON-RPC 2.0 and MCP specs the server MUST NOT reply with a
/// JSON-RPC response body. The HTTP wrapper acknowledges with 202 and
/// an empty body.
Notification,
/// The HTTP request authenticated, but the OAuth2 bearer token lacks the
/// delegated scope needed by this JSON-RPC method or tool.
Forbidden {
body: Value,
required_scope: Option<&'static str>,
},
}
fn log_mcp_computer_app_resource_delivery(
uri: &str,
protocol_era: &str,
ui_capability_present: bool,
http_status: u16,
mcp_error_code: Option<i64>,
) {
tracing::info!(
target: "webcodex::mcp",
uri,
protocol_era,
ui_capability_present,
http_status,
mcp_error_code = mcp_error_code.unwrap_or(-1),
"mcp_computer_app_resource_delivery"
);
}
fn log_mcp_computer_app_resource_outcome(
uri: &str,
protocol_era: McpProtocolEra,
ui_capability_present: bool,
outcome: &McpOutcome,
) {
let (http_status, mcp_error_code) = match outcome {
McpOutcome::Ok(_) | McpOutcome::ArtifactExportStream { .. } => (200, None),
McpOutcome::BadRequest(body) => (400, body["error"]["code"].as_i64()),
McpOutcome::NotFound(body) => (404, body["error"]["code"].as_i64()),
McpOutcome::Notification => (202, None),
McpOutcome::Forbidden { .. } => (403, None),
};
log_mcp_computer_app_resource_delivery(
uri,
protocol::era_label(protocol_era),
ui_capability_present,
http_status,
mcp_error_code,
);
}
/// Payload-free measurements of the final MCP tool result, after surface
/// projection. UTF-8 text bytes and JSON bytes are proxies, never Host tokens.
/// The existing model_ergonomics metric continues to measure structured results.
fn mcp_tool_response_audit_summary(
result: &Value,
surface: request_policy::McpSurface,
) -> Option<Value> {
let content = result.get("content")?.as_array()?;
let mut text_utf8_bytes = 0_u64;
let mut text_blocks = 0_u64;
let mut non_text_blocks = 0_u64;
for block in content {
if block.get("type")?.as_str()? == "text" {
text_utf8_bytes = text_utf8_bytes
.checked_add(u64::try_from(block.get("text")?.as_str()?.len()).ok()?)?;
text_blocks = text_blocks.checked_add(1)?;
} else {
non_text_blocks = non_text_blocks.checked_add(1)?;
}
}
let structured_json_bytes = result
.get("structuredContent")
.map(serialized_json_len)
.transpose()
.ok()?;
Some(json!({
"schema_version": 1,
"surface": match surface {
request_policy::McpSurface::Adaptive => "adaptive",
request_policy::McpSurface::Cli => "cli",
},
"result_json_bytes": serialized_json_len(result).ok()?,
"text_utf8_bytes": text_utf8_bytes,
"structured_json_bytes": structured_json_bytes,
"text_blocks": text_blocks,
"non_text_blocks": non_text_blocks,
}))
}
fn mcp_tools_list_audit_summary(
result: &Value,
protocol_era: McpProtocolEra,
compact_schemas: bool,
) -> Option<Value> {
let tools = result.get("tools")?.as_array()?;
let serialized_tools_bytes = serialized_json_len(&result["tools"]).ok()? as u64;
let serialized_result_bytes = serialized_json_len(result).ok()? as u64;
let gateway_tool_included = tools.iter().any(|tool| {
tool.get("name").and_then(Value::as_str) == Some(crate::mcp_gateway::MCP_TOOL_NAME)
});
Some(json!({
"transport": "mcp",
"tool_surface": {
"schema_version": 1,
"protocol_era": protocol::era_label(protocol_era),
"compact_schemas": compact_schemas,
"tool_count": tools.len() as u64,
"serialized_tools_bytes": serialized_tools_bytes,
"serialized_result_bytes": serialized_result_bytes,
"gateway_tool_included": gateway_tool_included
}
}))
}
#[handler]
pub async fn mcp_info(req: &mut Request, depot: &mut Depot, res: &mut Response) {
let Some(config) = crate::auth::get_config(depot) else {
res.status_code(StatusCode::INTERNAL_SERVER_ERROR);
res.render(json_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Server configuration not available",
));
return;
};
if let Err((status, _, message)) =
crate::public_ingress_auth::require_authority(req, depot, &config)
{
let status = StatusCode::from_u16(status).unwrap_or(StatusCode::FORBIDDEN);
res.status_code(status);
res.render(json_error(status, message));
return;
}
if request_header(req, MCP_PROTOCOL_VERSION_HEADER) == Some(MCP_STATELESS_PROTOCOL_VERSION) {
res.status_code(StatusCode::METHOD_NOT_ALLOWED);
return;
}
let auth_required = config.is_auth_enabled();
res.render(Json(json!({
"name": "webcodex",
"version": env!("CARGO_PKG_VERSION"),
"protocol": "mcp",
"protocolVersion": MCP_PROTOCOL_VERSION,
"transport": "streamable-http-jsonrpc",
"endpoint": "/mcp",
"methods": MCP_INFO_METHODS,
"auth": {
"type": "bearer",
"required": auth_required,
"header": "Authorization: Bearer <shared_key_or_wc_pat>"
}
})));
}
#[derive(Debug, Clone, Default)]
struct McpToolJobAuditCorrelation {
async_job_id: Option<String>,
observed_job_ids: Vec<String>,
resolved_project: Option<String>,
}
fn safe_audit_job_id(value: Option<&Value>) -> Option<String> {
value
.and_then(Value::as_str)
.map(str::trim)
.filter(|job_id| webcodex_core::workflow_session_contract::is_safe_job_id(job_id))
.map(str::to_string)
}
fn safe_audit_project(value: Option<&Value>) -> Option<String> {
value
.and_then(Value::as_str)
.map(str::trim)
.filter(|project| {
!project.is_empty()
&& project.chars().count() <= 512
&& !project.chars().any(char::is_control)
})
.map(str::to_string)
}
fn mcp_tool_job_audit_correlation(
tool_name: Option<&str>,
body: &Value,
) -> McpToolJobAuditCorrelation {
let Some(output) = body.pointer("/result/structuredContent/output") else {
return McpToolJobAuditCorrelation::default();
};
if tool_name == Some("wait_for_job_readiness") {
let mut observed_job_ids = Vec::new();
for value in output
.get("ready")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|item| item.get("job_id"))
.chain(
output
.get("pending_job_ids")
.and_then(Value::as_array)
.into_iter()
.flatten(),
)
.take(8)
{
if let Some(id) = safe_audit_job_id(Some(value)) {
if !observed_job_ids.contains(&id) {
observed_job_ids.push(id);
}
}
}
// Never infer Project authority from the sparse readiness result body.
// The Job dispatcher may already bind a common Project from exact caller-authorized
// Job records; mixed/projectless sets deliberately remain unanchored.
return McpToolJobAuditCorrelation {
observed_job_ids,
..Default::default()
};
}
if tool_name == Some("observe_jobs") {
let mut observed_job_ids = Vec::new();
let mut resolved_project: Option<String> = None;
let mut project_ambiguous = false;
if let Some(items) = output.get("items").and_then(Value::as_array) {
for item in items.iter().take(8) {
let original_item = item.get("details").unwrap_or(item);
let item_output = original_item
.get("output")
.filter(|value| value.is_object());
let job_id = safe_audit_job_id(
item.pointer("/execution/job_id")
.or_else(|| original_item.get("job_id"))
.or_else(|| item_output.and_then(|output| output.get("job_id"))),
);
if let Some(job_id) = job_id {
if !observed_job_ids.contains(&job_id) {
observed_job_ids.push(job_id);
}
let project = safe_audit_project(
item_output
.and_then(|output| output.get("project"))
.or_else(|| original_item.get("project")),
);
match (resolved_project.as_deref(), project.as_deref()) {
(None, Some(project)) if !project_ambiguous => {
resolved_project = Some(project.to_string());
}
(Some(existing), Some(project)) if existing == project => {}
(_, None) | (Some(_), Some(_)) => {
resolved_project = None;
project_ambiguous = true;
}
(None, Some(_)) => {}
}
}
}
}
return McpToolJobAuditCorrelation {
async_job_id: None,
observed_job_ids,
resolved_project: (!project_ambiguous).then_some(resolved_project).flatten(),
};
}
// Reuse the canonical audit predicate, including uncertain promoted Jobs;
// presentation outcome alone must not drop the original receipt identity.
let execution_facts = output.get("execution").map(|execution| {
json!({
"job_id": execution.get("job_id"),
"execution_state": execution.get("state"),
"promoted_to_job": output.pointer("/details/promoted_to_job")
})
});
McpToolJobAuditCorrelation {
async_job_id: crate::tool_runtime::job_audit::execution_job_id_for_audit(
tool_name,
execution_facts.as_ref().unwrap_or(output),
),
observed_job_ids: Vec::new(),
resolved_project: None,
}
}
fn mcp_tool_action_audit_ids(
success: bool,
observed_goal_plan_id: Option<&str>,
correlation: &crate::tool_runtime::ToolCallCorrelation,
jobs: Option<&McpToolJobAuditCorrelation>,
) -> Option<Value> {
if !success {
return None;
}
let mut ids = serde_json::Map::new();
if let Some(goal_id) = observed_goal_plan_id {
ids.insert("goal_id".to_string(), Value::String(goal_id.to_string()));
}
if let Some(session_id) = correlation.business_session_id.as_deref() {
ids.insert(
"business_session_id".to_string(),
Value::String(session_id.to_string()),
);
}
if let Some(jobs) = jobs {
if let Some(job_id) = jobs.async_job_id.as_deref() {
ids.insert(
"async_job_id".to_string(),
Value::String(job_id.to_string()),
);
}
if !jobs.observed_job_ids.is_empty() {
ids.insert(
"observed_job_ids".to_string(),
Value::Array(
jobs.observed_job_ids
.iter()
.cloned()
.map(Value::String)
.collect(),
),
);
}
}
(!ids.is_empty()).then_some(Value::Object(ids))
}
tokio::task_local! {
static REQUEST_PUBLIC_ORIGIN: Option<String>;
}
pub(super) fn app_public_origin(runtime: &ToolRuntime) -> Option<String> {
REQUEST_PUBLIC_ORIGIN
.try_with(Clone::clone)
.ok()
.flatten()
.or_else(|| runtime.runtime_info.configured_public_url.clone())
}
#[handler]
pub async fn mcp_post(req: &mut Request, depot: &mut Depot, res: &mut Response) {
let mut guard = ToolRequestLifecycle::new("mcp", new_trace_id(), "-", "POST /mcp", None);
guard.received();
let Some(authority_config) = crate::auth::get_config(depot) else {
let status = StatusCode::INTERNAL_SERVER_ERROR;
guard.parsed("http_validation_error");
guard.response_serialized(
status.as_u16(),
None,
Some(false),
None,
"http_validation_error",
);
res.status_code(status);
res.render(json_error(status, "Server configuration not available"));
guard.handler_returned(
status.as_u16(),
None,
Some(false),
None,
"http_validation_error",
);
return;
};
if let Err((status, _, message)) =
crate::public_ingress_auth::require_json_authority(req, depot, &authority_config)
{
let status = StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_REQUEST);
guard.parsed("http_validation_error");
guard.response_serialized(
status.as_u16(),
None,
Some(false),
None,
"http_validation_error",
);
res.status_code(status);
res.render(json_error(status, message));
guard.handler_returned(
status.as_u16(),
None,
Some(false),
None,
"http_validation_error",
);
return;
}
let Some(runtime) = runtime(depot) else {
// Size unknown without building the json_error body for measurement.
guard.response_serialized(500, None, Some(false), None, "error_runtime_missing");
res.status_code(StatusCode::INTERNAL_SERVER_ERROR);
res.render(json_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Tool runtime not configured",
));
guard.handler_returned(500, None, Some(false), None, "error_runtime_missing");
return;
};
let request: JsonRpcRequest = match req.parse_json().await {
Ok(request) => request,
Err(e) => {
guard.set_jsonrpc_id("none");
guard.parsed("parse_error");
let body = rpc_error(None, -32700, format!("Parse error: {}", e));
let estimated = estimate_json_bytes(&body);
guard.response_serialized(400, estimated, Some(false), None, "parse_error");
res.status_code(StatusCode::BAD_REQUEST);
res.render(Json(body));
guard.handler_returned(400, estimated, Some(false), None, "parse_error");
return;
}
};
guard.set_jsonrpc_id(jsonrpc_id_safe(request.id.as_ref()));
guard.set_method(request.method.clone());
let tool_name = if request.method == "tools/call" {
tools::tool_name_from_params(&request.params)
} else {
None
};
guard.set_tool_name(tool_name.clone());
guard.set_app_call_id(tools::agent_continuation_app_call_id_from_params(
&request.params,
));
let computer_app_resource_uri = if request.method == "resources/read" {
request
.params
.get("uri")
.and_then(Value::as_str)
.filter(|uri| *uri == app_registry::MCP_COMPUTER_UI_RESOURCE_URI)
.map(str::to_string)
} else {
None
};
let computer_app_ui_capability_present = resources::request_supports_mcp_apps(&request.params);
// Computer App resource delivery is part of gray-card diagnosis, but its
// durable projection must remain metadata-only. Never persist App HTML,
// screenshot/tool-result content, tool arguments, window titles, or other
// request payload fields here.
let computer_app_resource_audit = computer_app_resource_uri.as_ref().and_then(|uri| {
request.id.as_ref().map(|_| {
(
ActionAudit::start(req, depot, "/mcp", "resourcesRead"),
uri.clone(),
)
})
});
let record_computer_app_resource_audit =
|protocol_era: &str, status: StatusCode, mcp_error_code: Option<i64>| {
if let Some((audit, uri)) = computer_app_resource_audit.as_ref() {
audit.record(
ActionAuditRecord::new(
"computer_app_resource_read",
status.is_success(),
status,
)
.summary(json!({
"transport": "mcp",
"resource_uri": uri,
"resource_version": uri.rsplit('/').next().unwrap_or("unknown"),
"protocol_era": protocol_era,
"ui_capability_present": computer_app_ui_capability_present,
"mcp_error_code": mcp_error_code,
})),
);
}
};
let protocol_era = match validate_http_protocol(req, &request) {
Ok(protocol_era) => protocol_era,
Err(body) => {
guard.parsed("protocol_error");
if let Some(uri) = computer_app_resource_uri.as_deref() {
log_mcp_computer_app_resource_delivery(
uri,
"validation_failed",
computer_app_ui_capability_present,
400,
body["error"]["code"].as_i64(),
);
record_computer_app_resource_audit(
"validation_failed",
StatusCode::BAD_REQUEST,
body["error"]["code"].as_i64(),
);
}
let estimated = estimate_json_bytes(&body);
guard.response_serialized(400, estimated, Some(false), None, "protocol_error");
res.status_code(StatusCode::BAD_REQUEST);
res.render(Json(body));
guard.handler_returned(400, estimated, Some(false), None, "protocol_error");
return;
}
};
let (policy_selection, surface, default_project) =
match request_policy::resolve(req.headers(), runtime.mcp_host_policy).and_then(|policy| {
let surface = request_policy::resolve_surface(req.headers())?;
let project = request_policy::resolve_default_project(req.headers(), surface)?;
Ok((policy, surface, project))
}) {
Ok(selection) => selection,
Err(message) => {
// Reject ambiguous transport preferences before any tool/Job effect.
// Do not echo potentially sensitive header values into diagnostics.
guard.parsed("request_policy_error");
let body = rpc_error(request.id.clone(), -32600, message);
let estimated = estimate_json_bytes(&body);
guard.response_serialized(
400,
estimated,
Some(false),
None,
"request_policy_error",
);
res.status_code(StatusCode::BAD_REQUEST);
res.render(Json(body));
guard.handler_returned(400, estimated, Some(false), None, "request_policy_error");
return;
}
};
let policy = policy_selection.effective;
// Equal explicit profiles still have request-header provenance. Clone only
// the lightweight view when policy or its diagnostic source differs; shared
// stores, execution ownership and the deployment snapshot remain unchanged.
let runtime = if policy == runtime.mcp_host_policy
&& policy_selection.profile_source == runtime.mcp_host_profile_source
{
runtime
} else {
Arc::new(
runtime
.as_ref()
.clone()
.with_request_mcp_host_policy(policy_selection),
)
};
let auth = depot.obtain::<crate::auth::AuthContext>().ok().cloned();
let window = match crate::client_window::mcp_window(
req,
&request.params,
auth.as_ref(),
protocol_era == McpProtocolEra::Legacy,
request.method == "initialize",
) {
Ok(window) => window,
Err(message) => {
guard.parsed("client_window_error");
let body = rpc_error(request.id.clone(), -32600, message);
let estimated = estimate_json_bytes(&body);
guard.response_serialized(400, estimated, Some(false), None, "client_window_error");
res.status_code(StatusCode::BAD_REQUEST);
res.render(Json(body));
guard.handler_returned(400, estimated, Some(false), None, "client_window_error");
return;
}
};
// A host may list tools on throwaway legacy connections. Preserve the
// audit, but do not turn transport-session discovery into a ghost Window.
// Explicit ChatGPT/Codex/header Window discovery remains liveness evidence.
let observed_window = window
.identity
.as_ref()
.filter(|identity| request.method != "tools/list" || identity.source() != "mcp");
guard.set_client_window(observed_window);
guard.capture_mcp_host_policy(&policy_selection);
guard.parsed("ok");
let server_trace_id = guard.correlation_trace_id();
let window_registry = runtime.window_activity_registry();
let window_activity_visible = !work_result_app_internal_tool(tool_name.as_deref());
let mut live_window_request = if window_activity_visible
&& request.id.is_some()
&& matches!(request.method.as_str(), "tools/call" | "tools/list")
{
observed_window.map(|identity| {
window_registry.start_authenticated(
identity,
&server_trace_id,
&request.method,
tool_name.as_deref(),
auth.as_ref(),
guard.request_observed_at_ms(),
)
})
} else {
None
};
// Chat-window MCP tool calls must land in the action audit exactly like
// the REST surface (they were previously invisible there). Summary-level
// only: tool name and project — never arguments or outputs. JSON-RPC
// notifications are acknowledged but never dispatched, so they must not be
// represented as executed actions.
let audit = if request.method == "tools/call" && request.id.is_some() {
let audit = ActionAudit::start(req, depot, "/mcp", "toolsCall");
// Presentation stays out of live activity, but its durable Window binding
// is required when the Host later opens the empty-argument thread panel.
let audit =
if window_activity_visible || tool_name.as_deref() == Some("present_work_result") {
audit.with_window(window.identity.as_ref(), Some(&server_trace_id))
} else {
audit
};
Some((
audit,
tool_name.clone().unwrap_or_else(|| "unknown".to_string()),
tools::project_from_tool_call_params(&request.params),
))
} else {
None
};
let observed_goal_plan_id = goal_plan_observation_id(tool_name.as_deref(), &request.params);
let build_audit_event = |success: bool,
status: StatusCode,
error: Option<String>,
model_ergonomics: Option<&ModelErgonomicsRecord>,
correlation: &crate::tool_runtime::ToolCallCorrelation,
jobs: Option<&McpToolJobAuditCorrelation>|
-> Option<(
ActionAuditRecord,
crate::action_audit::ActionAuditRecordTiming,
)> {
if let Some((audit, tool, project)) = audit.as_ref() {
let mut summary = json!({ "transport": "mcp" });
if let Some(telemetry) =
model_ergonomics.and_then(|record| serde_json::to_value(record).ok())
{
summary["model_ergonomics"] = telemetry;
}
if let Some(composition) = correlation.code_mode_composition_audit_summary() {
summary["code_mode_composition"] = composition;
}
if let Some(expectation) = &correlation.failure_expectation_result {
summary["failure_expectation_result"] = json!(expectation);
}
if let Some(job_trace) = correlation.job_audit_summary() {
summary["job_trace"] = job_trace;
}
let mut event = ActionAuditRecord::new(tool.clone(), success, status)
.error(error)
.summary(summary)
.meaningful(
webcodex_tool_contracts::runtime_tool_activity_interaction(tool)
.is_meaningful(),
)
.recorder_gap(correlation.recorder_gap_session_id.clone());
if let Some(ids) = mcp_tool_action_audit_ids(
success,
observed_goal_plan_id.as_deref(),
correlation,
jobs,
) {
event = event.ids(ids);
}
event.project = correlation
.resolved_project
.clone()
.or_else(|| project.clone());
for link in &correlation.workflow_sessions {
let relation = match link.relation {
crate::tool_runtime::WorkflowSessionCorrelationRelation::Recording => {
crate::action_audit_sessions::WorkflowSessionRelation::Recording
}
crate::tool_runtime::WorkflowSessionCorrelationRelation::WorkOnProject => {
crate::action_audit_sessions::WorkflowSessionRelation::WorkOnProject
}
};
event =
event.workflow_link(link.session_id.clone(), relation, link.project.clone());
}
Some((event, audit.capture_record_timing()))
} else {
None
}
};
let tools_list_audit = if request.method == "tools/list" && request.id.is_some() {
Some(
ActionAudit::start(req, depot, "/mcp", "toolsList")
.with_window(observed_window, Some(&server_trace_id)),
)
} else {
None
};
let compact_schemas = runtime.runtime_info.mcp_compact_schemas;
let server_mcp_apps_enabled = runtime.runtime_info.mcp_apps_enabled;
let config = crate::auth::get_config(depot);
let db = crate::auth::get_db(depot);
let host_file_import_trust = tools::host_file_import_trust_for_call(
tool_name.as_deref(),
auth.as_ref(),
config.as_deref(),
db.as_deref(),
);
// Defense-in-depth backstop: every tool bounds its own agent/subprocess
// waits at <= 124s, so this outer limit never preempts a legitimate inner
// timeout. It only fires if a dispatch path hangs without a bound (the
// failure mode behind "MCP request never gets a reply"), converting a
// silently dead HTTP request into an observable JSON-RPC error.
let request_id = request.id.clone();
// The shared kernel timer is authoritative for completed runtime calls. Keep
// one outer emergency timer only so the MCP hard-timeout path does not erase
// an otherwise established runtime invocation from ergonomics telemetry.
let mut hard_timeout_model_ergonomics = tool_name.as_deref().and_then(|name| {
let mut timer =
ModelErgonomicsTimer::start_with_arguments(name, &request.params["arguments"])?;
timer.resolve_work_on_project_guidance_profile(policy, true);
Some(timer)
});
let mut tool_correlation = crate::tool_runtime::ToolCallCorrelation::default();
let mut model_ergonomics = None;
// Window liveness needs request correlation even when trace retention is off.
let active_trace_id = Some(server_trace_id.clone());
// Keep the complete MCP dispatch future off the current thread's stack. The
// handler state spans every method arm,
// so nesting it inline under tracing + timeout can exhaust the default
// ~2 MiB libtest/Tokio worker stack even when a request takes another arm.
let outcome = match tokio::time::timeout(
MCP_DISPATCH_HARD_TIMEOUT,
REQUEST_PUBLIC_ORIGIN.scope(
crate::public_ingress_auth::entry(depot).map(|entry| entry.origin.clone()),
scope_active_trace(
active_trace_id,
Box::pin(handle_mcp_request_for_surface(
&runtime,
request,
auth.as_ref(),
protocol_era,
host_file_import_trust,
window.identity.as_ref(),
Some(&mut guard),
Some(&mut model_ergonomics),
compact_schemas,
server_mcp_apps_enabled,
Some(&mut tool_correlation),
surface,
default_project.as_deref(),
)),
),
),
)
.await
{
Ok(outcome) => outcome,
Err(_) => {
let body = rpc_error(
request_id,
-32000,
format!(
"server-side dispatch exceeded {}s hard limit; the tool may still be running — check session/job status before retrying",
MCP_DISPATCH_HARD_TIMEOUT.as_secs()
),
);
if let Some(uri) = computer_app_resource_uri.as_deref() {
log_mcp_computer_app_resource_delivery(