Sync ctx 648d9f6 (part 2)
Browse filesGitHub commit: 648d9f6989ca91b93d26dd38fef42259cce4d7e2
- qa/bug_smoke_status.csv +11 -0
- qa/feature_status.csv +0 -0
- qa/tool-selection-token-history/tracker.csv +2 -2
- src/ctx/adapters/generic/ctx_core_tools.py +7 -3
- src/ctx/adapters/generic/runtime_lifecycle.py +27 -10
- src/ctx/adapters/generic/tools/mcp_router.py +125 -17
- src/ctx/api.py +2 -1
- src/ctx/cli/run.py +252 -56
- src/ctx/dashboard_docs.py +16 -2
- src/ctx/mcp_server/server.py +43 -2
- src/ctx/monitor/api/readonly.py +1 -1
- src/ctx/telemetry/__init__.py +41 -2
qa/bug_smoke_status.csv
CHANGED
|
@@ -14,3 +14,14 @@ AUDIT-012,UX Bug,Dashboard wiki,pack mode local overlays and entity typing,src/c
|
|
| 14 |
AUDIT-013,Tracker Hygiene,Canonical bug tracker,fixed-row next_action evidence,qa/bug_smoke_status.csv,local tracker audit found fixed rows still pointing at already completed PR or backlog actions,Low,Fixed and retested tracker rows should not tell future agents to rerun already completed PR or backlog actions.,manual tracker audit + csv parser validation,Retested Pass,Fixed rows included stale next_action values such as Run PR CI after commit and Continue dashboard/wiki backlog after PRs were merged,"Canonical tracker next_action text was stale for closed rows, making status summaries look unfinished.",Parse qa/bug_smoke_status.csv and inspect fixed rows whose next_action is not a closed-state instruction.,Normalize fixed-row next_action values to a closed discovery handoff and document this tracker cleanup row.,Fixed,.venv/bin/pytest src/tests/test_bug_smoke_tracker.py -q --tb=short,PASS: tracker parser enforces PASS retest evidence and closed next_action values.,2026-07-05,Codex,Reviewed by local static audit,Ponytail: tracker text only; no product behavior change.,Closed; continue repo-wide discovery.
|
| 15 |
AUDIT-014,Tracker Hygiene,Feature status ledger,DIST-004 supporting tracker status,docs/qa/feature-user-story-status.csv; qa/feature_status.csv,parallel docs audit found docs tracker status Needs Fix while canonical row was Blocked/Human Decision,Low,Supporting feature tracker and canonical feature status should agree on human-owned blocked release states.,parallel docs tracker audit + csv parser validation,Retested Pass,docs tracker DIST-004 status drift from canonical status,Supporting docs tracker kept historical Needs Fix wording for human-owned HF token rotation.,Compare DIST-004 in docs/qa/feature-user-story-status.csv and qa/feature_status.csv before fix.,Align supporting DIST-004 status with canonical Blocked/Human Decision and remove the override contract.,Fixed,.venv/bin/pytest src/tests/test_feature_user_story_tracker.py -q --tb=short,PASS: DIST-004 supporting tracker now matches canonical Blocked/Human Decision.,2026-07-05,Codex,Reviewed by local static audit,Ponytail: tracker text only; human-owned HF token rotation remains out of scope.,Closed; continue repo-wide discovery.
|
| 16 |
AUDIT-015,CI Gate,Public docs tracker,docs and publish workflows,.github/workflows/docs.yml; .github/workflows/publish.yml; src/tests/test_feature_user_story_tracker.py,parallel docs audit found docs and publish workflows ran only two of four public tracker suites,Medium,Public docs and release workflows should run the same four tracker suites as PR docs and local preflight.,parallel docs workflow audit + regression test,Retested Pass,docs/publish tracker commands omitted bug-smoke and toolbox suites,Docs deploy and publish canaries could miss bug tracker or toolbox tracker regressions.,Inspect workflow pytest commands and compare to PUBLIC_DOCS_TRACKER_TESTS.,Add bug-smoke and toolbox tracker suites to docs and publish workflow commands and enforce by regression.,Fixed,.venv/bin/pytest src/tests/test_feature_user_story_tracker.py src/tests/test_ci_preflight.py -q --tb=short,"PASS: workflows include bug-smoke, feature, dashboard, and toolbox tracker suites.",2026-07-05,Codex,Reviewed by local static audit,Ponytail: align duplicated workflow test lists with the established public tracker suites.,Closed; continue repo-wide discovery.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
AUDIT-013,Tracker Hygiene,Canonical bug tracker,fixed-row next_action evidence,qa/bug_smoke_status.csv,local tracker audit found fixed rows still pointing at already completed PR or backlog actions,Low,Fixed and retested tracker rows should not tell future agents to rerun already completed PR or backlog actions.,manual tracker audit + csv parser validation,Retested Pass,Fixed rows included stale next_action values such as Run PR CI after commit and Continue dashboard/wiki backlog after PRs were merged,"Canonical tracker next_action text was stale for closed rows, making status summaries look unfinished.",Parse qa/bug_smoke_status.csv and inspect fixed rows whose next_action is not a closed-state instruction.,Normalize fixed-row next_action values to a closed discovery handoff and document this tracker cleanup row.,Fixed,.venv/bin/pytest src/tests/test_bug_smoke_tracker.py -q --tb=short,PASS: tracker parser enforces PASS retest evidence and closed next_action values.,2026-07-05,Codex,Reviewed by local static audit,Ponytail: tracker text only; no product behavior change.,Closed; continue repo-wide discovery.
|
| 15 |
AUDIT-014,Tracker Hygiene,Feature status ledger,DIST-004 supporting tracker status,docs/qa/feature-user-story-status.csv; qa/feature_status.csv,parallel docs audit found docs tracker status Needs Fix while canonical row was Blocked/Human Decision,Low,Supporting feature tracker and canonical feature status should agree on human-owned blocked release states.,parallel docs tracker audit + csv parser validation,Retested Pass,docs tracker DIST-004 status drift from canonical status,Supporting docs tracker kept historical Needs Fix wording for human-owned HF token rotation.,Compare DIST-004 in docs/qa/feature-user-story-status.csv and qa/feature_status.csv before fix.,Align supporting DIST-004 status with canonical Blocked/Human Decision and remove the override contract.,Fixed,.venv/bin/pytest src/tests/test_feature_user_story_tracker.py -q --tb=short,PASS: DIST-004 supporting tracker now matches canonical Blocked/Human Decision.,2026-07-05,Codex,Reviewed by local static audit,Ponytail: tracker text only; human-owned HF token rotation remains out of scope.,Closed; continue repo-wide discovery.
|
| 16 |
AUDIT-015,CI Gate,Public docs tracker,docs and publish workflows,.github/workflows/docs.yml; .github/workflows/publish.yml; src/tests/test_feature_user_story_tracker.py,parallel docs audit found docs and publish workflows ran only two of four public tracker suites,Medium,Public docs and release workflows should run the same four tracker suites as PR docs and local preflight.,parallel docs workflow audit + regression test,Retested Pass,docs/publish tracker commands omitted bug-smoke and toolbox suites,Docs deploy and publish canaries could miss bug tracker or toolbox tracker regressions.,Inspect workflow pytest commands and compare to PUBLIC_DOCS_TRACKER_TESTS.,Add bug-smoke and toolbox tracker suites to docs and publish workflow commands and enforce by regression.,Fixed,.venv/bin/pytest src/tests/test_feature_user_story_tracker.py src/tests/test_ci_preflight.py -q --tb=short,"PASS: workflows include bug-smoke, feature, dashboard, and toolbox tracker suites.",2026-07-05,Codex,Reviewed by local static audit,Ponytail: align duplicated workflow test lists with the established public tracker suites.,Closed; continue repo-wide discovery.
|
| 17 |
+
AUDIT-016,CLI Bug,MCP ingest,malformed JSONL and checkpoint recovery,src/mcp_ingest.py; src/tests/test_mcp_ingest.py,Aquinas worker and local audit found malformed JSONL/non-object records were warned or skipped and corrupt scalar/nested checkpoint member shapes could poison checkpoint recovery.,Medium,"Malformed JSONL and non-object JSON should be current-run failures with a nonzero dry-run exit, while corrupt checkpoint scalar/nested member shapes reset fresh.",parallel worker audit + focused pytest,Retested Pass,malformed JSONL warned or skipped and corrupt checkpoint shapes could survive recovery before fix,MCP ingest could under-report malformed inputs and recover badly from corrupt checkpoint member shapes.,Run ctx-mcp-ingest dry-run against malformed JSONL/non-object JSON and corrupt checkpoint scalar/nested member shapes before the fix.,"Record malformed input as current-run failures, return nonzero in dry-run, and reset corrupt checkpoint member shapes fresh.",Fixed,.venv/bin/pytest src/tests/test_mcp_ingest.py -q --tb=short,PASS: integrated MCP ingest suite reported 30 passed; malformed input and checkpoint recovery regressions are covered.,2026-07-05,Codex,Reviewed by local tests + static audit,Ponytail: harden malformed input and checkpoint recovery only; no ingest feature expansion.,Closed; continue repo-wide discovery.
|
| 18 |
+
AUDIT-017,Telemetry,Runtime lifecycle,token usage metric span correlation,src/ctx/adapters/generic/runtime_lifecycle.py; src/tests/test_harness_ctx_core.py,Planck trace-propagation audit found lifecycle token-usage metrics were emitted before the lifecycle telemetry span.,Medium,Lifecycle token-usage metrics should share the trace/span of the lifecycle event they describe.,parallel trace audit + focused pytest,Retested Pass,usage metric point could correlate to the parent CLI span instead of the lifecycle event span before fix,Runtime lifecycle usage metrics were not emitted inside the lifecycle event span.,Record token_usage through ctx__mark_entity_used and compare metric trace/span attributes with the lifecycle event before the fix.,Move usage metric recording into the existing lifecycle telemetry span while preserving exact/estimated/unavailable attribution.,Fixed,.venv/bin/pytest src/tests/test_harness_ctx_core.py -q --tb=short,PASS: runtime lifecycle focused suite reported 74 passed including lifecycle usage metric span correlation.,2026-07-05,Codex,Reviewed by local tests + static audit,Ponytail: correlate existing metric emission with the lifecycle span; no new token accounting model.,Closed; continue repo-wide discovery.
|
| 19 |
+
AUDIT-018,Telemetry,CLI runtime,ctx run/resume early failure trace metadata,src/ctx/cli/run.py; src/tests/test_harness_cli_run.py,Rawls worker and Planck audit found ctx run/resume early failure paths could exit without failed CLI telemetry or previous trace correlation.,Medium,ctx run/resume should emit failed CLI telemetry inside a span for early failures and resume should include previous trace correlation when available.,parallel trace audit + focused pytest,Retested Pass,early validation/planner/session-create/session-load/session-attach/missing-model failures lacked complete CLI telemetry before fix,CLI early failures and resume flows had incomplete trace metadata.,Trigger ctx run validation/planner/session-create failures or ctx resume load/attach/missing-model failures before the fix and inspect ctx.cli.run/ctx.cli.resume telemetry.,"Wrap early failure exits in telemetry spans, hash/redact error payloads, persist initial_trace_id, and emit ctx.session.previous_trace_id on resume.",Fixed,.venv/bin/pytest src/tests/test_harness_cli_run.py -q --tb=short,PASS: focused CLI harness suite reported 73 passed and covered early failure/resume trace telemetry.,2026-07-05,Codex,Reviewed by local tests + static audit,Ponytail: telemetry-only hardening of existing failure paths; no CLI command behavior expansion.,Closed; continue repo-wide discovery.
|
| 20 |
+
AUDIT-019,Telemetry,MCP runtime,external MCP tool call trace propagation,src/ctx/adapters/generic/tools/mcp_router.py; src/ctx/mcp_server/server.py; src/ctx/telemetry/__init__.py; src/tests/test_mcp_router.py; src/tests/test_enterprise_telemetry.py,Jason worker and Planck audit found external MCP tool calls lacked client-side telemetry and spawned server spans did not inherit the caller trace.,High,External MCP tool calls should emit ctx.mcp.external_tool_call telemetry and propagate W3C traceparent metadata so server spans parent to the client request trace.,parallel trace audit + focused pytest,Retested Pass,MCP JSON-RPC calls lacked traceparent metadata and client-side external-call events before fix,External MCP calls broke end-to-end trace correlation across the router/server boundary.,Call an external MCP tool inside an active telemetry span before the fix and inspect request _meta plus server span parentage.,"Emit safe external-call telemetry, inject _meta.traceparent and hashed session correlation, parse traceparent on the MCP server, and parent server spans to the caller trace.",Fixed,.venv/bin/pytest src/tests/test_mcp_router.py src/tests/test_enterprise_telemetry.py -q --tb=short,"PASS: focused MCP router and enterprise telemetry suites reported 115 passed with external-call event, traceparent injection, and server span parenting coverage.",2026-07-05,Codex,Reviewed by local tests + static audit,Ponytail: trace propagation and telemetry only; sync stdio router semantics preserved.,Closed; continue repo-wide discovery.
|
| 21 |
+
AUDIT-020,Tracker Hygiene,Canonical feature tracker,stale post-merge validation prose,qa/feature_status.csv; docs/qa/feature-user-story-status.csv,Repo-wide audit found merged rows still using obsolete no-mistakes queue wording and old test-inventory prose after PR #238 and PR #239 merged.,Low,Canonical trackers should reflect current merged validation state and current README/docs test inventory without stale pending-gate prose.,manual tracker audit + rg/csv scan,Retested Pass,Rows referenced old gate-pending wording and old inventory after no-mistakes/CI/merge had completed.,Feature trackers had stale post-merge validation and inventory prose.,Scan qa/feature_status.csv and docs/qa/feature-user-story-status.csv for obsolete no-mistakes queue wording or old test-inventory references after PR #238/#239.,"Normalize affected validation/review notes to merged no-mistakes runs and current 4,473 inventory; keep human-owned HF token blocker status unchanged.",Fixed,.venv/bin/pytest src/tests/test_bug_smoke_tracker.py src/tests/test_feature_user_story_tracker.py -q --tb=short && .venv/bin/python src/update_repo_stats.py --check,PASS: tracker and stats checks passed for normalized post-merge tracker prose.,2026-07-05,Codex,Reviewed by local tracker audit,Ponytail: tracker text only; preserve human-owned HF token blocker and existing behavior.,Closed; continue repo-wide discovery.
|
| 22 |
+
AUDIT-021,Privacy,MCP router,omitted resource URI summary,src/ctx/adapters/generic/tools/mcp_router.py; src/tests/test_mcp_router.py,Runtime audit found _flatten_content emitted raw MCP resource URIs in omitted resource summaries.,High,Omitted MCP resource blocks should not expose local paths or private URIs to model-facing tool output.,parallel runtime audit + focused pytest,Retested Pass,MCP resource summaries included raw file/private URI strings before fix.,Omitted MCP resources leaked resource identifiers in flattened tool output.,Call _flatten_content with a resource block whose URI is a private file URL before the fix.,Replace raw URI summaries with a stable omitted-resource marker and assert private URI text is absent.,Fixed,.venv/bin/python -m pytest src/tests/test_mcp_router.py::TestFlattenContent -q --tb=short,PASS: TestFlattenContent reported 7 passed with private URI omission regression.,2026-07-05,Codex,Reviewed by local tests + static audit,Ponytail: redact omitted resource summary only; preserve text image and unknown-block behavior.,Closed; continue repo-wide discovery.
|
| 23 |
+
AUDIT-022,CLI Reliability,MCP ingest,JSONL replay preloads file,src/mcp_ingest.py; src/tests/test_mcp_ingest.py,Runtime audit found _iter_records_from used read_text().splitlines() despite the streaming JSONL contract.,Medium,ctx-mcp-ingest --from-jsonl should iterate line by line without preloading the full file.,parallel runtime audit + focused pytest,Retested Pass,JSONL file replay read the entire file before yielding records.,Large MCP catalogs could consume unnecessary memory during JSONL ingest.,Monkeypatch Path.read_text to fail and iterate --from-jsonl records before the fix.,Stream --from-jsonl with Path.open() and add a regression proving read_text is not called.,Fixed,.venv/bin/python -m pytest src/tests/test_mcp_ingest.py -q --tb=short,PASS: MCP ingest suite reported 32 passed with JSONL streaming regression.,2026-07-05,Codex,Reviewed by local tests + static audit,Ponytail: align implementation with existing streaming contract; no ingest behavior expansion.,Closed; continue repo-wide discovery.
|
| 24 |
+
AUDIT-023,CLI UX,MCP ingest,--status creates wiki path,src/mcp_ingest.py; src/tests/test_mcp_ingest.py,Runtime audit found ctx-mcp-ingest --status called ensure_wiki before printing checkpoint status.,Medium,ctx-mcp-ingest --status should read checkpoint state and exit without creating a wiki for a mistyped or missing path.,parallel runtime audit + focused pytest,Retested Pass,--status created the wiki directory before reporting checkpoint status.,Read-only status command mutated the filesystem for missing wiki paths.,Run ctx-mcp-ingest --status with a missing --wiki path and inspect whether the path is created before the fix.,Handle --status before ensure_wiki and add a regression that the missing wiki path remains absent.,Fixed,.venv/bin/python -m pytest src/tests/test_mcp_ingest.py -q --tb=short,PASS: MCP ingest suite reported 32 passed with no-mutation status regression.,2026-07-05,Codex,Reviewed by local tests + static audit,Ponytail: reorder read-only status path only; normal ingest still initializes wiki.,Closed; continue repo-wide discovery.
|
| 25 |
+
AUDIT-024,Security,Dashboard docs,entity-encoded active URL attributes,src/ctx/dashboard_docs.py; src/tests/test_security_hardening.py,Dashboard audit found entity-encoded active schemes survived docs sanitization in URL-bearing attributes.,High,Docs HTML sanitization should neutralize active URL schemes after entity decoding and control-character stripping.,parallel dashboard audit + focused pytest,Retested Pass,Entity-encoded javascript and data HTML schemes survived in href src xlink:href or formaction before fix.,Docs sanitization missed encoded active URL schemes in URL-bearing attributes.,Render sanitized docs HTML with entity-encoded active schemes in href src xlink:href and formaction before the fix.,Decode and normalize URL-bearing attribute values before active-scheme checks and cover the four attributes.,Fixed,.venv/bin/python -m pytest src/tests/test_security_hardening.py -q --tb=short,PASS: security hardening suite reported 41 passed with encoded active URL regressions.,2026-07-05,Codex,Reviewed by worker tests + local static audit,Ponytail: sanitize URL-bearing attributes only; preserve safe tabbed-input behavior.,Closed; continue repo-wide discovery.
|
| 26 |
+
AUDIT-025,API Correctness,Monitor readonly API,HTML 404 for missing skill sidecar,src/ctx/monitor/api/readonly.py; src/tests/test_ctx_monitor.py,Dashboard audit found /api/skill/<slug>.json returned an HTML 404 body when the sidecar was missing.,Medium,JSON API routes should return JSON error payloads for missing resources.,parallel dashboard audit + focused pytest,Retested Pass,Missing skill sidecar API response had text/html content before fix.,Readonly skill API returned HTML for a JSON endpoint failure.,GET /api/skill/missing-sidecar.json before the fix and inspect status content type and body.,Return a JSON detail payload with 404 status for missing sidecars and add monitor regression coverage.,Fixed,.venv/bin/python -m pytest src/tests/test_ctx_monitor.py::test_skill_sidecar_api_missing_sidecar_returns_json_404 src/tests/test_ctx_monitor.py::test_skill_sidecar_api_reads_typed_sidecar -q,PASS: focused monitor API sidecar tests reported 2 passed.,2026-07-05,Codex,Reviewed by worker tests + local static audit,Ponytail: route-local JSON error only; no dispatcher refactor.,Closed; continue repo-wide discovery.
|
| 27 |
+
AUDIT-026,Privacy,Core wiki tool,absolute wiki path in model-facing output,src/ctx/adapters/generic/ctx_core_tools.py; src/tests/test_harness_ctx_core.py,Runtime audit found ctx__wiki_get returned absolute wiki filesystem paths in success and missing-page outputs.,High,Model-facing wiki fetch results should expose wiki-relative paths or candidate labels without host absolute paths.,parallel runtime audit + focused pytest,Retested Pass,ctx__wiki_get success path and looked_in candidates included host absolute wiki paths before fix.,Wiki fetch tool leaked local filesystem layout into persisted tool results.,Call ctx__wiki_get for an existing page or missing slug under a temp wiki before the fix and inspect JSON output.,Return wiki-relative entity paths for success and missing candidates and assert temp absolute paths are absent.,Fixed,.venv/bin/python -m pytest src/tests/test_harness_ctx_core.py::TestWikiGet -q,PASS: TestWikiGet reported 6 passed with absolute-path privacy regressions.,2026-07-05,Codex,Reviewed by worker tests + local static audit,Ponytail: replace host paths with existing wiki-relative entity paths only.,Closed; continue repo-wide discovery.
|
qa/feature_status.csv
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
qa/tool-selection-token-history/tracker.csv
CHANGED
|
@@ -3,8 +3,8 @@ US-001,API/CLI/UI,Tool recommendation selection,"As a programmer or AI engineer,
|
|
| 3 |
US-002,API/CLI/UI,TLDR descriptions,"As a user, I can read a concise TLDR for each suggested tool before selecting it.","Each recommendation has a short description plus relevance reason; fallback uses safe existing metadata when description is absent.","src/ctx/core/resolve/recommendations.py; src/ctx/adapters/generic/ctx_core_tools.py; src/ctx/cli/recommend.py","pytest src/tests/test_recommendations.py src/tests/test_recommendation_surfaces_golden.py -q",Retested Pass,High,4,2026-07-02,"Phase 1 adds API/core tldr and reason fallbacks from existing row metadata; Phase 4A renders CLI tldr/reason; Phase 5B renders TLDR and reason text on the dashboard /recommend page; Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19)."
|
| 4 |
US-003,Knowledge Graph,Related recommendations after partial selection,"As a user, if I select only some suggestions, ctx proposes related tools.","Related rows are generated from graph/category/tag neighbors, exclude selected/rejected/unavailable/deprecated rows, and include reason text.","src/ctx/core/resolve/recommendations.py; src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py","pytest src/tests/test_recommendations.py src/tests/test_harness_recommendations.py -q",Retested Pass,High,6,2026-07-02,"Phase 2A adds ctx__recommend_related; Phase 2B1 adds public ctx.recommend_related with redacted selection telemetry; Phase 2B2 adds LoopFlow/agent-loop related_recommendations; Phase 4A adds CLI related recommendations; Phase 5B adds dashboard related suggestions for partial selections; Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19)."
|
| 5 |
US-004,Runtime Lifecycle,Tool activation tracking,"As a user, selected tool activation is recorded with session/system context.","Activation records include entity id/name/type, timestamp, privacy-safe session context, user-selected vs system-selected source, and source context.","src/ctx/adapters/generic/runtime_lifecycle.py; src/ctx/adapters/generic/ctx_core_tools.py","pytest src/tests/test_harness_ctx_core.py -q",Retested Pass,Critical,2,2026-07-02,"Phase 3A adds selected, selection_source, and sanitized source_context to load_entity/session_state and keeps local lifecycle history when telemetry is disabled; Phase 7 passed focused harness-core retest (70 passed), full pytest (4431 passed, 2 skipped), and ci_preflight --profile pr (19/19)."
|
| 6 |
-
US-005,Telemetry,Token usage KPI,"As a user, I can see token usage per selected and activated tool.",
|
| 7 |
US-006,Persistence,Historical usage,"As a user, I can view historical token usage per tool over time.","Usage history persists across sessions and can be aggregated by tool, type, session, and source.","src/ctx/adapters/generic/runtime_lifecycle.py; src/ctx/monitor/services/runtime.py","pytest src/tests/test_harness_ctx_core.py src/tests/test_ctx_monitor.py -q",Retested Pass,High,3,2026-07-02,"Phase 3B persists per-entity token_usage summaries in runtime session_state; Phase 5A aggregates lifecycle history by selection source, active loads, token totals, attribution, and recent tool usage for dashboard/API consumers; Phase 8 pins MCP unavailable usage in by-tool/by-type/by-session/by-source history; Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19)."
|
| 8 |
US-007,Dashboard,Dashboard support,"As a user/admin, I can see tool-selection and token-history KPIs in the dashboard.","Dashboard shows totals, recent usage, history, user-vs-system selected source, and empty/error/unavailable states.","src/ctx/monitor/services/runtime.py; src/ctx/monitor/pages/activity.py; src/ctx/monitor/pages/ops.py; src/ctx/monitor/api/readonly.py","pytest src/tests/test_ctx_monitor.py src/tests/test_monitor_testing_api.py src/tests/test_dashboard_smoke.py -q",Retested Pass,High,3,2026-07-02,"Phase 5A extends the existing Runtime page/API with tool-selection totals, source split, token totals, attribution counts, and recent usage; Phase 5B adds dashboard recommendation selection and related-suggestion controls; Phase 7 browser monitor security gate passed (11 passed) and ci_preflight --profile pr passed 19/19."
|
| 9 |
US-008,Parity,API/CLI/UI parity,"As a user, behavior is consistent across API, CLI, MCP/core toolbox, LoopFlow, and dashboard.","Shared semantics are reused; differences are documented only where necessary.","src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py; src/ctx/mcp_server/server.py; src/ctx/adapters/loopflow.py; docs","pytest src/tests/test_public_api.py src/tests/test_mcp_server.py src/tests/test_loopflow_adapter.py -q",Retested Pass,High,8,2026-07-02,"Phase 1 preserves recommend_bundle; Phase 2 adds MCP/core, Python API, and LoopFlow related recommendations; Phase 4A adds CLI parity for IDs, TLDR, reasons, selected/rejected inputs, and related rows; Phase 5A adds runtime dashboard/API parity for persisted selection and token usage; Phase 5B adds dashboard recommendation parity; Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19)."
|
| 10 |
-
QA-001,QA,Regression suite,"As a maintainer, I can ship without breaking existing recommendation/telemetry/dashboard behavior.","Focused milestone tests, ruff, mypy, full pytest, ci_preflight, and no-mistakes pass.","src/tests; scripts/ci_preflight.py; no-mistakes gate","python scripts/ci_preflight.py --profile pr; no-mistakes axi run --intent ...",
|
|
|
|
| 3 |
US-002,API/CLI/UI,TLDR descriptions,"As a user, I can read a concise TLDR for each suggested tool before selecting it.","Each recommendation has a short description plus relevance reason; fallback uses safe existing metadata when description is absent.","src/ctx/core/resolve/recommendations.py; src/ctx/adapters/generic/ctx_core_tools.py; src/ctx/cli/recommend.py","pytest src/tests/test_recommendations.py src/tests/test_recommendation_surfaces_golden.py -q",Retested Pass,High,4,2026-07-02,"Phase 1 adds API/core tldr and reason fallbacks from existing row metadata; Phase 4A renders CLI tldr/reason; Phase 5B renders TLDR and reason text on the dashboard /recommend page; Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19)."
|
| 4 |
US-003,Knowledge Graph,Related recommendations after partial selection,"As a user, if I select only some suggestions, ctx proposes related tools.","Related rows are generated from graph/category/tag neighbors, exclude selected/rejected/unavailable/deprecated rows, and include reason text.","src/ctx/core/resolve/recommendations.py; src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py","pytest src/tests/test_recommendations.py src/tests/test_harness_recommendations.py -q",Retested Pass,High,6,2026-07-02,"Phase 2A adds ctx__recommend_related; Phase 2B1 adds public ctx.recommend_related with redacted selection telemetry; Phase 2B2 adds LoopFlow/agent-loop related_recommendations; Phase 4A adds CLI related recommendations; Phase 5B adds dashboard related suggestions for partial selections; Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19)."
|
| 5 |
US-004,Runtime Lifecycle,Tool activation tracking,"As a user, selected tool activation is recorded with session/system context.","Activation records include entity id/name/type, timestamp, privacy-safe session context, user-selected vs system-selected source, and source context.","src/ctx/adapters/generic/runtime_lifecycle.py; src/ctx/adapters/generic/ctx_core_tools.py","pytest src/tests/test_harness_ctx_core.py -q",Retested Pass,Critical,2,2026-07-02,"Phase 3A adds selected, selection_source, and sanitized source_context to load_entity/session_state and keeps local lifecycle history when telemetry is disabled; Phase 7 passed focused harness-core retest (70 passed), full pytest (4431 passed, 2 skipped), and ci_preflight --profile pr (19/19)."
|
| 6 |
+
US-005,Telemetry,Token usage KPI,"As a user, I can see token usage per selected and activated tool.",Exact input/output/total tokens are recorded only with per-tool correlation; session totals stay session-level; estimated/unavailable values are labeled honestly with reason; API/dashboard expose the data; lifecycle token-usage metrics share the lifecycle event trace/span.,src/ctx/adapters/generic/runtime_lifecycle.py; src/ctx/telemetry/__init__.py; src/ctx/cli/run.py,pytest src/tests/test_enterprise_telemetry.py src/tests/test_harness_cli_run.py src/tests/test_harness_ctx_core.py -q,Retested Pass,Critical,5,2026-07-05,Phase 3B adds token_usage to mark_entity_used with exact/estimated/unavailable attribution and emits OTel-style usage counters/histograms when metrics are enabled; Phase 4B labels ctx run usage as session-scoped/unavailable for per-tool attribution; Phase 5A exposes token totals/attribution on /runtime and /api/runtime.json; Phase 8 makes missing host token data a persisted unavailable usage record and adds explicit MCP telemetry/history coverage; Phase 9 correlates lifecycle usage metrics with the lifecycle event trace/span; focused lifecycle suite reported 74 passed.
|
| 7 |
US-006,Persistence,Historical usage,"As a user, I can view historical token usage per tool over time.","Usage history persists across sessions and can be aggregated by tool, type, session, and source.","src/ctx/adapters/generic/runtime_lifecycle.py; src/ctx/monitor/services/runtime.py","pytest src/tests/test_harness_ctx_core.py src/tests/test_ctx_monitor.py -q",Retested Pass,High,3,2026-07-02,"Phase 3B persists per-entity token_usage summaries in runtime session_state; Phase 5A aggregates lifecycle history by selection source, active loads, token totals, attribution, and recent tool usage for dashboard/API consumers; Phase 8 pins MCP unavailable usage in by-tool/by-type/by-session/by-source history; Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19)."
|
| 8 |
US-007,Dashboard,Dashboard support,"As a user/admin, I can see tool-selection and token-history KPIs in the dashboard.","Dashboard shows totals, recent usage, history, user-vs-system selected source, and empty/error/unavailable states.","src/ctx/monitor/services/runtime.py; src/ctx/monitor/pages/activity.py; src/ctx/monitor/pages/ops.py; src/ctx/monitor/api/readonly.py","pytest src/tests/test_ctx_monitor.py src/tests/test_monitor_testing_api.py src/tests/test_dashboard_smoke.py -q",Retested Pass,High,3,2026-07-02,"Phase 5A extends the existing Runtime page/API with tool-selection totals, source split, token totals, attribution counts, and recent usage; Phase 5B adds dashboard recommendation selection and related-suggestion controls; Phase 7 browser monitor security gate passed (11 passed) and ci_preflight --profile pr passed 19/19."
|
| 9 |
US-008,Parity,API/CLI/UI parity,"As a user, behavior is consistent across API, CLI, MCP/core toolbox, LoopFlow, and dashboard.","Shared semantics are reused; differences are documented only where necessary.","src/ctx/api.py; src/ctx/adapters/generic/ctx_core_tools.py; src/ctx/mcp_server/server.py; src/ctx/adapters/loopflow.py; docs","pytest src/tests/test_public_api.py src/tests/test_mcp_server.py src/tests/test_loopflow_adapter.py -q",Retested Pass,High,8,2026-07-02,"Phase 1 preserves recommend_bundle; Phase 2 adds MCP/core, Python API, and LoopFlow related recommendations; Phase 4A adds CLI parity for IDs, TLDR, reasons, selected/rejected inputs, and related rows; Phase 5A adds runtime dashboard/API parity for persisted selection and token usage; Phase 5B adds dashboard recommendation parity; Phase 7 passed full pytest (4431 passed, 2 skipped) and ci_preflight --profile pr (19/19)."
|
| 10 |
+
QA-001,QA,Regression suite,"As a maintainer, I can ship without breaking existing recommendation/telemetry/dashboard behavior.","Focused milestone tests, ruff, mypy, full pytest, ci_preflight, and no-mistakes pass.","src/tests; scripts/ci_preflight.py; no-mistakes gate","python scripts/ci_preflight.py --profile pr; no-mistakes axi run --intent ...",Retested Pass,Critical,11,2026-07-05,"Phase 2 slices passed; Phase 3A passed: 142 passed; Phase 3B usage persistence/metrics slice passed: 70 passed plus ruff, format, and mypy; Phase 4A CLI selection slice passed: 6 passed plus ruff, format, and mypy; Phase 4B runtime attribution slice passed: 72 passed plus ruff, format, and mypy; Phase 5A dashboard slice passed: 3 focused tests, 8 runtime monitor tests, 5 dashboard smoke/API tests plus ruff, format, and mypy; Phase 5B dashboard recommendation slice passed: 4 focused tests, full monitor 180 passed, ruff, format, and mypy; Phase 7 passed ruff format/check, mypy, full pytest (4431 passed, 2 skipped), ci_preflight --profile pr (19/19), stats check, docs build, public tracker tests, and final no-mistakes validation in run 01KWSCY4EF01EXWSHYB5SGS4BC; post-merge inventory cleanup PR #239 also passed."
|
src/ctx/adapters/generic/ctx_core_tools.py
CHANGED
|
@@ -474,7 +474,8 @@ class CtxCoreToolbox:
|
|
| 474 |
name=f"{_NAMESPACE}wiki_get",
|
| 475 |
description=(
|
| 476 |
"Fetch a single wiki entity page by slug. Returns "
|
| 477 |
-
"the full frontmatter (as a dict)
|
|
|
|
| 478 |
"Use after recommend_bundle / wiki_search to read "
|
| 479 |
"the detail of a specific candidate."
|
| 480 |
),
|
|
@@ -878,7 +879,10 @@ class CtxCoreToolbox:
|
|
| 878 |
return json.dumps(
|
| 879 |
{
|
| 880 |
"error": f"no entity page found for slug {slug!r}",
|
| 881 |
-
"looked_in": [
|
|
|
|
|
|
|
|
|
|
| 882 |
}
|
| 883 |
)
|
| 884 |
|
|
@@ -1003,7 +1007,7 @@ class CtxCoreToolbox:
|
|
| 1003 |
"slug": path.stem,
|
| 1004 |
"entity_type": entity_type,
|
| 1005 |
"wikilink": wikilink,
|
| 1006 |
-
"path":
|
| 1007 |
"frontmatter": fm,
|
| 1008 |
"body": body,
|
| 1009 |
},
|
|
|
|
| 474 |
name=f"{_NAMESPACE}wiki_get",
|
| 475 |
description=(
|
| 476 |
"Fetch a single wiki entity page by slug. Returns "
|
| 477 |
+
"the full frontmatter (as a dict), body text, and "
|
| 478 |
+
"wiki-relative path. "
|
| 479 |
"Use after recommend_bundle / wiki_search to read "
|
| 480 |
"the detail of a specific candidate."
|
| 481 |
),
|
|
|
|
| 879 |
return json.dumps(
|
| 880 |
{
|
| 881 |
"error": f"no entity page found for slug {slug!r}",
|
| 882 |
+
"looked_in": [
|
| 883 |
+
_wiki_entity_relpath(candidate_type, slug)
|
| 884 |
+
for candidate_type, _, _ in candidates
|
| 885 |
+
],
|
| 886 |
}
|
| 887 |
)
|
| 888 |
|
|
|
|
| 1007 |
"slug": path.stem,
|
| 1008 |
"entity_type": entity_type,
|
| 1009 |
"wikilink": wikilink,
|
| 1010 |
+
"path": _wiki_entity_relpath(entity_type, path.stem),
|
| 1011 |
"frontmatter": fm,
|
| 1012 |
"body": body,
|
| 1013 |
},
|
src/ctx/adapters/generic/runtime_lifecycle.py
CHANGED
|
@@ -1,4 +1,10 @@
|
|
| 1 |
-
"""Host-neutral runtime lifecycle logging for generic ctx integrations.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
@@ -33,6 +39,7 @@ _ESCALATION_STATUSES = {"open", "resolved", "ignored"}
|
|
| 33 |
_SELECTION_SOURCES = {"user", "system", "host", "unknown"}
|
| 34 |
_TOKEN_ATTRIBUTIONS = {"exact", "estimated", "unavailable"}
|
| 35 |
_LIFECYCLE_SANITIZER_CONFIG = {"enabled": True, "mode": "local_redacted"}
|
|
|
|
| 36 |
_PATH_SEGMENT_RE = r"[^/\s'\"`<>|:;,\)\]]+"
|
| 37 |
_UNIX_ABSOLUTE_PATH_RE = re.compile(rf"(?<![\w./-])/(?:{_PATH_SEGMENT_RE}/)+{_PATH_SEGMENT_RE}")
|
| 38 |
_TILDE_PATH_RE = re.compile(rf"(?<![\w./-])~/(?:{_PATH_SEGMENT_RE}/)*{_PATH_SEGMENT_RE}")
|
|
@@ -52,7 +59,7 @@ _SECURITY_SCAN_STATUSES = {
|
|
| 52 |
|
| 53 |
@dataclass(frozen=True)
|
| 54 |
class RuntimeLifecycleStore:
|
| 55 |
-
"""Append-only
|
| 56 |
|
| 57 |
root: Path | None = None
|
| 58 |
|
|
@@ -353,15 +360,23 @@ def _sanitize_lifecycle_event(event: dict[str, Any]) -> dict[str, Any]:
|
|
| 353 |
security_scan = redacted.get("security_scan")
|
| 354 |
if isinstance(security_scan, dict):
|
| 355 |
redacted["security_scan"] = _sanitize_security_scan(security_scan)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
cwd = redacted.pop("cwd", None)
|
| 357 |
if isinstance(cwd, str) and cwd:
|
| 358 |
redacted["cwd_hash"] = hash_identifier(cwd)
|
| 359 |
return redacted
|
| 360 |
|
| 361 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
def _sanitize_security_scan(raw: Any) -> Any:
|
| 363 |
if isinstance(raw, str):
|
| 364 |
-
return
|
| 365 |
if isinstance(raw, list):
|
| 366 |
return [_sanitize_security_scan(item) for item in raw]
|
| 367 |
if isinstance(raw, tuple):
|
|
@@ -388,14 +403,10 @@ def _validate_session_id(raw: str) -> str:
|
|
| 388 |
def _record_runtime_lifecycle_telemetry(event: dict[str, Any]) -> None:
|
| 389 |
token_usage = event.get("token_usage")
|
| 390 |
usage_attribution: str | None = None
|
|
|
|
| 391 |
if isinstance(token_usage, dict):
|
| 392 |
usage_attribution = str(token_usage.get("attribution") or "unavailable")
|
| 393 |
total_tokens = token_usage.get("total_tokens")
|
| 394 |
-
_record_token_usage_metrics(
|
| 395 |
-
event,
|
| 396 |
-
attribution=usage_attribution,
|
| 397 |
-
total_tokens=total_tokens if isinstance(total_tokens, int) else None,
|
| 398 |
-
)
|
| 399 |
payload: dict[str, Any] = {
|
| 400 |
"ctx.lifecycle.action": str(event.get("action") or ""),
|
| 401 |
"ctx.payload.present": bool(event.get("payload")),
|
|
@@ -430,10 +441,16 @@ def _record_runtime_lifecycle_telemetry(event: dict[str, Any]) -> None:
|
|
| 430 |
payload["ctx.usage.cost_usd"] = (
|
| 431 |
float(cost_value) if isinstance(cost_value, (int, float)) else None
|
| 432 |
)
|
| 433 |
-
if not telemetry_enabled():
|
| 434 |
-
return
|
| 435 |
try:
|
| 436 |
with telemetry_span():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 437 |
record_event(
|
| 438 |
"ctx.runtime_lifecycle.record",
|
| 439 |
source="ctx-runtime-lifecycle",
|
|
|
|
| 1 |
+
"""Host-neutral runtime lifecycle logging for generic ctx integrations.
|
| 2 |
+
|
| 3 |
+
Runtime lifecycle events are local operational records, but user- or
|
| 4 |
+
host-provided free text is still privacy-sensitive. The store redacts secrets
|
| 5 |
+
and local paths from top-level lifecycle text, nested payloads, source context,
|
| 6 |
+
and security-scan details before appending events.
|
| 7 |
+
"""
|
| 8 |
|
| 9 |
from __future__ import annotations
|
| 10 |
|
|
|
|
| 39 |
_SELECTION_SOURCES = {"user", "system", "host", "unknown"}
|
| 40 |
_TOKEN_ATTRIBUTIONS = {"exact", "estimated", "unavailable"}
|
| 41 |
_LIFECYCLE_SANITIZER_CONFIG = {"enabled": True, "mode": "local_redacted"}
|
| 42 |
+
_LIFECYCLE_FREE_TEXT_FIELDS = ("reason", "evidence", "command", "summary", "trigger", "status")
|
| 43 |
_PATH_SEGMENT_RE = r"[^/\s'\"`<>|:;,\)\]]+"
|
| 44 |
_UNIX_ABSOLUTE_PATH_RE = re.compile(rf"(?<![\w./-])/(?:{_PATH_SEGMENT_RE}/)+{_PATH_SEGMENT_RE}")
|
| 45 |
_TILDE_PATH_RE = re.compile(rf"(?<![\w./-])~/(?:{_PATH_SEGMENT_RE}/)*{_PATH_SEGMENT_RE}")
|
|
|
|
| 59 |
|
| 60 |
@dataclass(frozen=True)
|
| 61 |
class RuntimeLifecycleStore:
|
| 62 |
+
"""Append-only, privacy-redacted event store for custom/API/local harnesses."""
|
| 63 |
|
| 64 |
root: Path | None = None
|
| 65 |
|
|
|
|
| 360 |
security_scan = redacted.get("security_scan")
|
| 361 |
if isinstance(security_scan, dict):
|
| 362 |
redacted["security_scan"] = _sanitize_security_scan(security_scan)
|
| 363 |
+
for field in _LIFECYCLE_FREE_TEXT_FIELDS:
|
| 364 |
+
value = redacted.get(field)
|
| 365 |
+
if isinstance(value, str):
|
| 366 |
+
redacted[field] = _sanitize_free_text(value)
|
| 367 |
cwd = redacted.pop("cwd", None)
|
| 368 |
if isinstance(cwd, str) and cwd:
|
| 369 |
redacted["cwd_hash"] = hash_identifier(cwd)
|
| 370 |
return redacted
|
| 371 |
|
| 372 |
|
| 373 |
+
def _sanitize_free_text(text: str) -> str:
|
| 374 |
+
return _redact_path_text(redact_secret_text(text))
|
| 375 |
+
|
| 376 |
+
|
| 377 |
def _sanitize_security_scan(raw: Any) -> Any:
|
| 378 |
if isinstance(raw, str):
|
| 379 |
+
return _sanitize_free_text(raw)
|
| 380 |
if isinstance(raw, list):
|
| 381 |
return [_sanitize_security_scan(item) for item in raw]
|
| 382 |
if isinstance(raw, tuple):
|
|
|
|
| 403 |
def _record_runtime_lifecycle_telemetry(event: dict[str, Any]) -> None:
|
| 404 |
token_usage = event.get("token_usage")
|
| 405 |
usage_attribution: str | None = None
|
| 406 |
+
total_tokens: Any = None
|
| 407 |
if isinstance(token_usage, dict):
|
| 408 |
usage_attribution = str(token_usage.get("attribution") or "unavailable")
|
| 409 |
total_tokens = token_usage.get("total_tokens")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
payload: dict[str, Any] = {
|
| 411 |
"ctx.lifecycle.action": str(event.get("action") or ""),
|
| 412 |
"ctx.payload.present": bool(event.get("payload")),
|
|
|
|
| 441 |
payload["ctx.usage.cost_usd"] = (
|
| 442 |
float(cost_value) if isinstance(cost_value, (int, float)) else None
|
| 443 |
)
|
|
|
|
|
|
|
| 444 |
try:
|
| 445 |
with telemetry_span():
|
| 446 |
+
if isinstance(token_usage, dict) and usage_attribution is not None:
|
| 447 |
+
_record_token_usage_metrics(
|
| 448 |
+
event,
|
| 449 |
+
attribution=usage_attribution,
|
| 450 |
+
total_tokens=total_tokens if isinstance(total_tokens, int) else None,
|
| 451 |
+
)
|
| 452 |
+
if not telemetry_enabled():
|
| 453 |
+
return
|
| 454 |
record_event(
|
| 455 |
"ctx.runtime_lifecycle.record",
|
| 456 |
source="ctx-runtime-lifecycle",
|
src/ctx/adapters/generic/tools/mcp_router.py
CHANGED
|
@@ -50,6 +50,13 @@ from dataclasses import dataclass, field
|
|
| 50 |
from typing import Any, Iterator
|
| 51 |
|
| 52 |
from ctx.adapters.generic.providers.base import ToolDefinition
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
_logger = logging.getLogger(__name__)
|
| 55 |
|
|
@@ -90,6 +97,69 @@ _TOKEN_VALUE_RE = re.compile(
|
|
| 90 |
)
|
| 91 |
|
| 92 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
def _default_child_env() -> dict[str, str]:
|
| 94 |
"""Return parent env entries that are process plumbing, not credentials."""
|
| 95 |
child_env: dict[str, str] = {}
|
|
@@ -254,8 +324,9 @@ class McpClient:
|
|
| 254 |
``call_tool`` calls on the same client are serialized by a lock.
|
| 255 |
"""
|
| 256 |
|
| 257 |
-
def __init__(self, config: McpServerConfig) -> None:
|
| 258 |
self._config = config
|
|
|
|
| 259 |
self._proc: subprocess.Popen[bytes] | None = None
|
| 260 |
self._lock = threading.Lock()
|
| 261 |
self._next_id = 0
|
|
@@ -404,16 +475,48 @@ class McpClient:
|
|
| 404 |
|
| 405 |
Raises ``McpServerError`` when the server reports an error.
|
| 406 |
"""
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
)
|
| 416 |
-
|
| 417 |
|
| 418 |
# ── JSON-RPC plumbing ─────────────────────────────────────────────────
|
| 419 |
|
|
@@ -434,7 +537,7 @@ class McpClient:
|
|
| 434 |
"jsonrpc": "2.0",
|
| 435 |
"id": request_id,
|
| 436 |
"method": method,
|
| 437 |
-
"params": params
|
| 438 |
}
|
| 439 |
try:
|
| 440 |
self._write_frame(request)
|
|
@@ -580,8 +683,14 @@ class McpRouter:
|
|
| 580 |
distinguishes them.
|
| 581 |
"""
|
| 582 |
|
| 583 |
-
def __init__(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 584 |
self._configs = list(configs)
|
|
|
|
| 585 |
self._clients: dict[str, McpClient] = {}
|
| 586 |
self._started = False
|
| 587 |
|
|
@@ -594,7 +703,7 @@ class McpRouter:
|
|
| 594 |
for cfg in self._configs:
|
| 595 |
if cfg.name in self._clients:
|
| 596 |
raise ValueError(f"duplicate MCP server name {cfg.name!r}")
|
| 597 |
-
client = McpClient(cfg)
|
| 598 |
client.start()
|
| 599 |
self._clients[cfg.name] = client
|
| 600 |
spawned.append(cfg.name)
|
|
@@ -680,8 +789,8 @@ def _flatten_content(content: list[Any] | None) -> str:
|
|
| 680 |
"""Concatenate a MCP tool-result content array into a single string.
|
| 681 |
|
| 682 |
Text blocks pass through verbatim. Non-text blocks (image/resource)
|
| 683 |
-
are summarised with a short tag;
|
| 684 |
-
|
| 685 |
"""
|
| 686 |
if not content:
|
| 687 |
return ""
|
|
@@ -697,8 +806,7 @@ def _flatten_content(content: list[Any] | None) -> str:
|
|
| 697 |
mime = block.get("mimeType", "image/*")
|
| 698 |
parts.append(f"[{mime} image omitted]")
|
| 699 |
elif btype == "resource":
|
| 700 |
-
|
| 701 |
-
parts.append(f"[resource: {uri}]")
|
| 702 |
else:
|
| 703 |
parts.append(f"[{btype or 'unknown'} block omitted]")
|
| 704 |
return "".join(parts)
|
|
|
|
| 50 |
from typing import Any, Iterator
|
| 51 |
|
| 52 |
from ctx.adapters.generic.providers.base import ToolDefinition
|
| 53 |
+
from ctx.telemetry import (
|
| 54 |
+
hash_identifier,
|
| 55 |
+
record_event,
|
| 56 |
+
telemetry_enabled,
|
| 57 |
+
telemetry_span,
|
| 58 |
+
traceparent_from_span,
|
| 59 |
+
)
|
| 60 |
|
| 61 |
_logger = logging.getLogger(__name__)
|
| 62 |
|
|
|
|
| 97 |
)
|
| 98 |
|
| 99 |
|
| 100 |
+
def _duration_ms(started: float) -> float:
|
| 101 |
+
return (time.perf_counter() - started) * 1000.0
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _current_trace_metadata(session_id: str | None) -> dict[str, str]:
|
| 105 |
+
if not telemetry_enabled():
|
| 106 |
+
return {}
|
| 107 |
+
meta: dict[str, str] = {}
|
| 108 |
+
traceparent = traceparent_from_span()
|
| 109 |
+
if traceparent is not None:
|
| 110 |
+
meta["traceparent"] = traceparent
|
| 111 |
+
if session_id:
|
| 112 |
+
meta["ctx.session.hash"] = hash_identifier(session_id)
|
| 113 |
+
return meta
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _params_with_metadata(
|
| 117 |
+
params: dict[str, Any] | None,
|
| 118 |
+
*,
|
| 119 |
+
session_id: str | None,
|
| 120 |
+
) -> dict[str, Any]:
|
| 121 |
+
out = dict(params or {})
|
| 122 |
+
meta = _current_trace_metadata(session_id)
|
| 123 |
+
if not meta:
|
| 124 |
+
return out
|
| 125 |
+
existing = out.get("_meta")
|
| 126 |
+
merged = dict(existing) if isinstance(existing, dict) else {}
|
| 127 |
+
merged.update(meta)
|
| 128 |
+
out["_meta"] = merged
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _record_mcp_client_tool_call(
|
| 133 |
+
*,
|
| 134 |
+
server: str,
|
| 135 |
+
tool: str,
|
| 136 |
+
session_id: str | None,
|
| 137 |
+
outcome: str,
|
| 138 |
+
duration_ms: float,
|
| 139 |
+
error_kind: str | None = None,
|
| 140 |
+
) -> None:
|
| 141 |
+
payload: dict[str, Any] = {
|
| 142 |
+
"rpc.system": "jsonrpc",
|
| 143 |
+
"rpc.method": "tools/call",
|
| 144 |
+
"mcp.server.name": server,
|
| 145 |
+
"mcp.tool.name": tool,
|
| 146 |
+
"otel.status_code": "ERROR" if outcome == "error" else "OK",
|
| 147 |
+
}
|
| 148 |
+
try:
|
| 149 |
+
record_event(
|
| 150 |
+
"ctx.mcp.external_tool_call",
|
| 151 |
+
source="ctx-mcp-router",
|
| 152 |
+
transport="mcp-jsonrpc",
|
| 153 |
+
session_id=session_id,
|
| 154 |
+
outcome=outcome,
|
| 155 |
+
duration_ms=duration_ms,
|
| 156 |
+
error_kind=error_kind,
|
| 157 |
+
payload=payload,
|
| 158 |
+
)
|
| 159 |
+
except Exception: # noqa: BLE001 - telemetry must never break tool execution.
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
|
| 163 |
def _default_child_env() -> dict[str, str]:
|
| 164 |
"""Return parent env entries that are process plumbing, not credentials."""
|
| 165 |
child_env: dict[str, str] = {}
|
|
|
|
| 324 |
``call_tool`` calls on the same client are serialized by a lock.
|
| 325 |
"""
|
| 326 |
|
| 327 |
+
def __init__(self, config: McpServerConfig, *, session_id: str | None = None) -> None:
|
| 328 |
self._config = config
|
| 329 |
+
self._session_id = str(session_id or "").strip() or None
|
| 330 |
self._proc: subprocess.Popen[bytes] | None = None
|
| 331 |
self._lock = threading.Lock()
|
| 332 |
self._next_id = 0
|
|
|
|
| 475 |
|
| 476 |
Raises ``McpServerError`` when the server reports an error.
|
| 477 |
"""
|
| 478 |
+
started = time.perf_counter()
|
| 479 |
+
recorded = False
|
| 480 |
+
with telemetry_span():
|
| 481 |
+
try:
|
| 482 |
+
result = self._request(
|
| 483 |
+
"tools/call",
|
| 484 |
+
{"name": name, "arguments": arguments},
|
| 485 |
+
)
|
| 486 |
+
if result.get("isError"):
|
| 487 |
+
content = _flatten_content(result.get("content", []))
|
| 488 |
+
_record_mcp_client_tool_call(
|
| 489 |
+
server=self._config.name,
|
| 490 |
+
tool=name,
|
| 491 |
+
session_id=self._session_id,
|
| 492 |
+
outcome="error",
|
| 493 |
+
duration_ms=_duration_ms(started),
|
| 494 |
+
error_kind="tool_error",
|
| 495 |
+
)
|
| 496 |
+
recorded = True
|
| 497 |
+
raise McpServerError(
|
| 498 |
+
f"tool '{name}' on '{self._config.name}' reported isError: {content}"
|
| 499 |
+
)
|
| 500 |
+
output = _flatten_content(result.get("content", []))
|
| 501 |
+
except Exception as exc:
|
| 502 |
+
if not recorded:
|
| 503 |
+
_record_mcp_client_tool_call(
|
| 504 |
+
server=self._config.name,
|
| 505 |
+
tool=name,
|
| 506 |
+
session_id=self._session_id,
|
| 507 |
+
outcome="error",
|
| 508 |
+
duration_ms=_duration_ms(started),
|
| 509 |
+
error_kind=type(exc).__name__,
|
| 510 |
+
)
|
| 511 |
+
raise
|
| 512 |
+
_record_mcp_client_tool_call(
|
| 513 |
+
server=self._config.name,
|
| 514 |
+
tool=name,
|
| 515 |
+
session_id=self._session_id,
|
| 516 |
+
outcome="ok",
|
| 517 |
+
duration_ms=_duration_ms(started),
|
| 518 |
)
|
| 519 |
+
return output
|
| 520 |
|
| 521 |
# ── JSON-RPC plumbing ─────────────────────────────────────────────────
|
| 522 |
|
|
|
|
| 537 |
"jsonrpc": "2.0",
|
| 538 |
"id": request_id,
|
| 539 |
"method": method,
|
| 540 |
+
"params": _params_with_metadata(params, session_id=self._session_id),
|
| 541 |
}
|
| 542 |
try:
|
| 543 |
self._write_frame(request)
|
|
|
|
| 683 |
distinguishes them.
|
| 684 |
"""
|
| 685 |
|
| 686 |
+
def __init__(
|
| 687 |
+
self,
|
| 688 |
+
configs: list[McpServerConfig],
|
| 689 |
+
*,
|
| 690 |
+
session_id: str | None = None,
|
| 691 |
+
) -> None:
|
| 692 |
self._configs = list(configs)
|
| 693 |
+
self._session_id = str(session_id or "").strip() or None
|
| 694 |
self._clients: dict[str, McpClient] = {}
|
| 695 |
self._started = False
|
| 696 |
|
|
|
|
| 703 |
for cfg in self._configs:
|
| 704 |
if cfg.name in self._clients:
|
| 705 |
raise ValueError(f"duplicate MCP server name {cfg.name!r}")
|
| 706 |
+
client = McpClient(cfg, session_id=self._session_id)
|
| 707 |
client.start()
|
| 708 |
self._clients[cfg.name] = client
|
| 709 |
spawned.append(cfg.name)
|
|
|
|
| 789 |
"""Concatenate a MCP tool-result content array into a single string.
|
| 790 |
|
| 791 |
Text blocks pass through verbatim. Non-text blocks (image/resource)
|
| 792 |
+
are summarised with a short tag; resource URIs are deliberately
|
| 793 |
+
omitted so local paths and private identifiers do not leak.
|
| 794 |
"""
|
| 795 |
if not content:
|
| 796 |
return ""
|
|
|
|
| 806 |
mime = block.get("mimeType", "image/*")
|
| 807 |
parts.append(f"[{mime} image omitted]")
|
| 808 |
elif btype == "resource":
|
| 809 |
+
parts.append("[resource omitted]")
|
|
|
|
| 810 |
else:
|
| 811 |
parts.append(f"[{btype or 'unknown'} block omitted]")
|
| 812 |
return "".join(parts)
|
src/ctx/api.py
CHANGED
|
@@ -334,7 +334,8 @@ def wiki_get(
|
|
| 334 |
``entity_type`` optionally disambiguates duplicate slugs across
|
| 335 |
skills, agents, MCP servers, and harnesses.
|
| 336 |
|
| 337 |
-
Result dict on hit: ``slug``, ``path``,
|
|
|
|
| 338 |
Errors (invalid slug, traversal attempt, file missing) all map to
|
| 339 |
``None`` — library callers get a simple "exists or not" contract.
|
| 340 |
"""
|
|
|
|
| 334 |
``entity_type`` optionally disambiguates duplicate slugs across
|
| 335 |
skills, agents, MCP servers, and harnesses.
|
| 336 |
|
| 337 |
+
Result dict on hit: ``slug``, wiki-relative ``path``,
|
| 338 |
+
``frontmatter``, ``body``.
|
| 339 |
Errors (invalid slug, traversal attempt, file missing) all map to
|
| 340 |
``None`` — library callers get a simple "exists or not" contract.
|
| 341 |
"""
|
src/ctx/cli/run.py
CHANGED
|
@@ -28,6 +28,7 @@ import json
|
|
| 28 |
import logging
|
| 29 |
import math
|
| 30 |
import os
|
|
|
|
| 31 |
import shlex
|
| 32 |
import sys
|
| 33 |
import time
|
|
@@ -68,6 +69,7 @@ _GITHUB_MCP_CREDENTIAL_ENV = (
|
|
| 68 |
"GITHUB_TOKEN",
|
| 69 |
"GH_TOKEN",
|
| 70 |
)
|
|
|
|
| 71 |
|
| 72 |
|
| 73 |
# ── Provider key-env defaults ───────────────────────────────────────────────
|
|
@@ -561,6 +563,45 @@ def _run_start_payload(
|
|
| 561 |
}
|
| 562 |
|
| 563 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 564 |
def _resume_start_payload(
|
| 565 |
args: argparse.Namespace,
|
| 566 |
*,
|
|
@@ -571,8 +612,9 @@ def _resume_start_payload(
|
|
| 571 |
restored_mcp_count: int,
|
| 572 |
allow_count: int,
|
| 573 |
deny_count: int,
|
|
|
|
| 574 |
) -> dict[str, Any]:
|
| 575 |
-
|
| 576 |
"ctx.model": model,
|
| 577 |
"ctx.task.length": len(str(args.task or "")),
|
| 578 |
"ctx.ctx_tools.enabled": use_ctx_tools,
|
|
@@ -582,6 +624,22 @@ def _resume_start_payload(
|
|
| 582 |
"ctx.tool_policy.allow_count": allow_count,
|
| 583 |
"ctx.tool_policy.deny_count": deny_count,
|
| 584 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 585 |
|
| 586 |
|
| 587 |
def _loop_result_payload(result: Any) -> dict[str, Any]:
|
|
@@ -952,11 +1010,21 @@ def _build_parser() -> argparse.ArgumentParser:
|
|
| 952 |
|
| 953 |
|
| 954 |
def _cmd_run(args: argparse.Namespace) -> int:
|
|
|
|
| 955 |
profile_error = _apply_model_profile_defaults(args)
|
| 956 |
if profile_error:
|
| 957 |
print(profile_error, file=sys.stderr)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 958 |
return 2
|
| 959 |
-
telemetry_started = time.perf_counter()
|
| 960 |
|
| 961 |
sdir = Path(args.sessions_dir) if args.sessions_dir else default_sessions_dir()
|
| 962 |
|
|
@@ -969,7 +1037,21 @@ def _cmd_run(args: argparse.Namespace) -> int:
|
|
| 969 |
)
|
| 970 |
|
| 971 |
session_id = args.session_id or new_session_id()
|
| 972 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 973 |
|
| 974 |
# Planner pass (opt-in, SOLO path only — when --evaluator is set,
|
| 975 |
# run_with_evaluation owns the planner call so the P/G/E agents
|
|
@@ -984,7 +1066,21 @@ def _cmd_run(args: argparse.Namespace) -> int:
|
|
| 984 |
provider,
|
| 985 |
model=args.planner_model or args.model,
|
| 986 |
)
|
| 987 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 988 |
system_prompt = augmented_system_prompt(system_prompt, plan_artifact)
|
| 989 |
if not args.quiet:
|
| 990 |
status = "ok" if plan_artifact.parsed_ok else "unstructured"
|
|
@@ -999,11 +1095,25 @@ def _cmd_run(args: argparse.Namespace) -> int:
|
|
| 999 |
if ctx_tools_enabled:
|
| 1000 |
system_prompt = _with_ctx_session_instructions(system_prompt, session_id)
|
| 1001 |
|
| 1002 |
-
|
| 1003 |
-
|
| 1004 |
-
|
| 1005 |
-
|
| 1006 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1007 |
|
| 1008 |
# ctx-core tools.
|
| 1009 |
lifecycle = RuntimeLifecycleStore()
|
|
@@ -1034,52 +1144,73 @@ def _cmd_run(args: argparse.Namespace) -> int:
|
|
| 1034 |
"use --overwrite-session to replace it or ctx resume to continue it.",
|
| 1035 |
file=sys.stderr,
|
| 1036 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1037 |
return 1
|
| 1038 |
except ValueError as exc:
|
| 1039 |
print(f"error: {exc}", file=sys.stderr)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1040 |
return 1
|
| 1041 |
-
|
| 1042 |
-
|
| 1043 |
-
|
| 1044 |
-
|
| 1045 |
-
|
| 1046 |
-
|
| 1047 |
-
|
| 1048 |
-
|
| 1049 |
-
|
| 1050 |
-
|
| 1051 |
-
|
| 1052 |
-
|
| 1053 |
-
|
| 1054 |
-
|
| 1055 |
-
|
| 1056 |
-
|
| 1057 |
-
|
| 1058 |
-
|
| 1059 |
-
|
| 1060 |
-
|
| 1061 |
-
|
| 1062 |
-
|
| 1063 |
-
|
| 1064 |
-
|
| 1065 |
-
|
| 1066 |
-
|
| 1067 |
-
|
| 1068 |
-
|
| 1069 |
-
|
| 1070 |
-
|
| 1071 |
-
|
| 1072 |
-
|
| 1073 |
-
|
| 1074 |
-
|
| 1075 |
-
|
| 1076 |
-
|
| 1077 |
-
|
| 1078 |
-
|
| 1079 |
-
|
| 1080 |
-
|
| 1081 |
-
|
| 1082 |
-
|
|
|
|
| 1083 |
if ctx_tools_enabled:
|
| 1084 |
_record_lifecycle_safely(
|
| 1085 |
lifecycle,
|
|
@@ -1131,6 +1262,18 @@ def _cmd_run(args: argparse.Namespace) -> int:
|
|
| 1131 |
if args.contract and not args.planner:
|
| 1132 |
# Contracts refine planner output; without a plan
|
| 1133 |
# they'd have no prior spec to refine.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1134 |
raise SystemExit(
|
| 1135 |
"error: --contract requires --planner (the contract "
|
| 1136 |
"refines the planner's success_criteria into "
|
|
@@ -1300,19 +1443,47 @@ def _load_session_for_cli(session_id: str, sessions_dir: Path) -> Any | None:
|
|
| 1300 |
|
| 1301 |
|
| 1302 |
def _cmd_resume(args: argparse.Namespace) -> int:
|
|
|
|
| 1303 |
sdir = Path(args.sessions_dir) if args.sessions_dir else default_sessions_dir()
|
| 1304 |
state = _load_session_for_cli(args.session_id, sdir)
|
| 1305 |
if state is None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1306 |
return 1
|
| 1307 |
-
telemetry_started = time.perf_counter()
|
| 1308 |
|
| 1309 |
meta = state.metadata
|
|
|
|
| 1310 |
model = args.model or meta.get("model")
|
| 1311 |
if not model:
|
| 1312 |
print(
|
| 1313 |
f"error: session {args.session_id!r} has no recorded model; pass --model explicitly.",
|
| 1314 |
file=sys.stderr,
|
| 1315 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1316 |
return 1
|
| 1317 |
|
| 1318 |
use_ctx_tools = bool(meta.get("ctx_tools_enabled", True))
|
|
@@ -1348,7 +1519,25 @@ def _cmd_resume(args: argparse.Namespace) -> int:
|
|
| 1348 |
timeout=provider_timeout,
|
| 1349 |
)
|
| 1350 |
|
| 1351 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1352 |
observer = JsonlObserver(
|
| 1353 |
store,
|
| 1354 |
session_metadata={},
|
|
@@ -1362,7 +1551,7 @@ def _cmd_resume(args: argparse.Namespace) -> int:
|
|
| 1362 |
# transcript unless the user explicitly opts in for this resume.
|
| 1363 |
recorded_mcp_configs = _mcp_configs_from_metadata(meta)
|
| 1364 |
mcp_configs = recorded_mcp_configs if args.restore_session_mcp else []
|
| 1365 |
-
router = McpRouter(mcp_configs) if mcp_configs else None
|
| 1366 |
|
| 1367 |
lifecycle = RuntimeLifecycleStore()
|
| 1368 |
extra_tools: list[ToolDefinition] = []
|
|
@@ -1424,6 +1613,7 @@ def _cmd_resume(args: argparse.Namespace) -> int:
|
|
| 1424 |
restored_mcp_count=len(mcp_configs),
|
| 1425 |
allow_count=len(allow_tools),
|
| 1426 |
deny_count=len(deny_tools),
|
|
|
|
| 1427 |
),
|
| 1428 |
outcome="ok",
|
| 1429 |
duration_ms=_duration_ms(telemetry_started),
|
|
@@ -1464,7 +1654,10 @@ def _cmd_resume(args: argparse.Namespace) -> int:
|
|
| 1464 |
"ctx.cli.resume",
|
| 1465 |
session_id=args.session_id,
|
| 1466 |
phase="failed",
|
| 1467 |
-
payload=
|
|
|
|
|
|
|
|
|
|
| 1468 |
outcome="error",
|
| 1469 |
duration_ms=_duration_ms(telemetry_started),
|
| 1470 |
error_kind=type(exc).__name__,
|
|
@@ -1488,7 +1681,10 @@ def _cmd_resume(args: argparse.Namespace) -> int:
|
|
| 1488 |
"ctx.cli.resume",
|
| 1489 |
session_id=args.session_id,
|
| 1490 |
phase="finished",
|
| 1491 |
-
payload=
|
|
|
|
|
|
|
|
|
|
| 1492 |
outcome=outcome,
|
| 1493 |
duration_ms=_duration_ms(telemetry_started),
|
| 1494 |
error_kind=error_kind,
|
|
|
|
| 28 |
import logging
|
| 29 |
import math
|
| 30 |
import os
|
| 31 |
+
import re
|
| 32 |
import shlex
|
| 33 |
import sys
|
| 34 |
import time
|
|
|
|
| 69 |
"GITHUB_TOKEN",
|
| 70 |
"GH_TOKEN",
|
| 71 |
)
|
| 72 |
+
_TRACE_ID_RE = re.compile(r"^[0-9a-f]{32}$")
|
| 73 |
|
| 74 |
|
| 75 |
# ── Provider key-env defaults ───────────────────────────────────────────────
|
|
|
|
| 563 |
}
|
| 564 |
|
| 565 |
|
| 566 |
+
def _run_setup_failure_payload(args: argparse.Namespace, *, stage: str) -> dict[str, Any]:
|
| 567 |
+
model = args.model if isinstance(args.model, str) and args.model else None
|
| 568 |
+
provider_prefix = _model_provider_prefix(model) if model else None
|
| 569 |
+
payload: dict[str, Any] = {
|
| 570 |
+
"ctx.task.length": len(str(args.task or "")),
|
| 571 |
+
"ctx.ctx_tools.enabled": not args.no_ctx_tools,
|
| 572 |
+
"ctx.planner.enabled": bool(args.planner),
|
| 573 |
+
"ctx.evaluator.enabled": bool(args.evaluator),
|
| 574 |
+
"ctx.contract.enabled": bool(args.contract),
|
| 575 |
+
"ctx.run.failure_stage": stage,
|
| 576 |
+
}
|
| 577 |
+
if model:
|
| 578 |
+
payload["ctx.model"] = model
|
| 579 |
+
provider = args.provider or provider_prefix
|
| 580 |
+
if provider:
|
| 581 |
+
payload["ctx.provider"] = provider
|
| 582 |
+
if provider_prefix:
|
| 583 |
+
payload["ctx.provider_prefix"] = provider_prefix
|
| 584 |
+
return payload
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def _session_initial_trace_id(meta: dict[str, Any]) -> str | None:
|
| 588 |
+
value = meta.get("initial_trace_id") or meta.get("trace_id")
|
| 589 |
+
if not isinstance(value, str):
|
| 590 |
+
return None
|
| 591 |
+
if not _TRACE_ID_RE.fullmatch(value) or value == "0" * 32:
|
| 592 |
+
return None
|
| 593 |
+
return value
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def _with_previous_trace_id(
|
| 597 |
+
payload: dict[str, Any],
|
| 598 |
+
previous_trace_id: str | None,
|
| 599 |
+
) -> dict[str, Any]:
|
| 600 |
+
if previous_trace_id:
|
| 601 |
+
payload["ctx.session.previous_trace_id"] = previous_trace_id
|
| 602 |
+
return payload
|
| 603 |
+
|
| 604 |
+
|
| 605 |
def _resume_start_payload(
|
| 606 |
args: argparse.Namespace,
|
| 607 |
*,
|
|
|
|
| 612 |
restored_mcp_count: int,
|
| 613 |
allow_count: int,
|
| 614 |
deny_count: int,
|
| 615 |
+
previous_trace_id: str | None = None,
|
| 616 |
) -> dict[str, Any]:
|
| 617 |
+
payload = {
|
| 618 |
"ctx.model": model,
|
| 619 |
"ctx.task.length": len(str(args.task or "")),
|
| 620 |
"ctx.ctx_tools.enabled": use_ctx_tools,
|
|
|
|
| 624 |
"ctx.tool_policy.allow_count": allow_count,
|
| 625 |
"ctx.tool_policy.deny_count": deny_count,
|
| 626 |
}
|
| 627 |
+
return _with_previous_trace_id(payload, previous_trace_id)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def _resume_setup_failure_payload(
|
| 631 |
+
args: argparse.Namespace,
|
| 632 |
+
*,
|
| 633 |
+
stage: str,
|
| 634 |
+
previous_trace_id: str | None = None,
|
| 635 |
+
) -> dict[str, Any]:
|
| 636 |
+
payload: dict[str, Any] = {
|
| 637 |
+
"ctx.task.length": len(str(args.task or "")),
|
| 638 |
+
"ctx.run.failure_stage": stage,
|
| 639 |
+
}
|
| 640 |
+
if args.model:
|
| 641 |
+
payload["ctx.model"] = args.model
|
| 642 |
+
return _with_previous_trace_id(payload, previous_trace_id)
|
| 643 |
|
| 644 |
|
| 645 |
def _loop_result_payload(result: Any) -> dict[str, Any]:
|
|
|
|
| 1010 |
|
| 1011 |
|
| 1012 |
def _cmd_run(args: argparse.Namespace) -> int:
|
| 1013 |
+
telemetry_started = time.perf_counter()
|
| 1014 |
profile_error = _apply_model_profile_defaults(args)
|
| 1015 |
if profile_error:
|
| 1016 |
print(profile_error, file=sys.stderr)
|
| 1017 |
+
with telemetry_span():
|
| 1018 |
+
_record_cli_telemetry(
|
| 1019 |
+
"ctx.cli.run",
|
| 1020 |
+
session_id=args.session_id,
|
| 1021 |
+
phase="failed",
|
| 1022 |
+
payload=_run_setup_failure_payload(args, stage="validation"),
|
| 1023 |
+
outcome="error",
|
| 1024 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1025 |
+
error_kind="ValueError",
|
| 1026 |
+
)
|
| 1027 |
return 2
|
|
|
|
| 1028 |
|
| 1029 |
sdir = Path(args.sessions_dir) if args.sessions_dir else default_sessions_dir()
|
| 1030 |
|
|
|
|
| 1037 |
)
|
| 1038 |
|
| 1039 |
session_id = args.session_id or new_session_id()
|
| 1040 |
+
try:
|
| 1041 |
+
system_prompt = _resolve_system_prompt(args.system_prompt)
|
| 1042 |
+
except Exception as exc:
|
| 1043 |
+
with telemetry_span():
|
| 1044 |
+
_record_cli_telemetry(
|
| 1045 |
+
"ctx.cli.run",
|
| 1046 |
+
session_id=session_id,
|
| 1047 |
+
phase="failed",
|
| 1048 |
+
payload=_run_setup_failure_payload(args, stage="validation"),
|
| 1049 |
+
outcome="error",
|
| 1050 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1051 |
+
error_kind=type(exc).__name__,
|
| 1052 |
+
exc=exc,
|
| 1053 |
+
)
|
| 1054 |
+
raise
|
| 1055 |
|
| 1056 |
# Planner pass (opt-in, SOLO path only — when --evaluator is set,
|
| 1057 |
# run_with_evaluation owns the planner call so the P/G/E agents
|
|
|
|
| 1066 |
provider,
|
| 1067 |
model=args.planner_model or args.model,
|
| 1068 |
)
|
| 1069 |
+
try:
|
| 1070 |
+
plan_artifact = planner.plan(args.task)
|
| 1071 |
+
except Exception as exc:
|
| 1072 |
+
with telemetry_span():
|
| 1073 |
+
_record_cli_telemetry(
|
| 1074 |
+
"ctx.cli.run",
|
| 1075 |
+
session_id=session_id,
|
| 1076 |
+
phase="failed",
|
| 1077 |
+
payload=_run_setup_failure_payload(args, stage="planner"),
|
| 1078 |
+
outcome="error",
|
| 1079 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1080 |
+
error_kind=type(exc).__name__,
|
| 1081 |
+
exc=exc,
|
| 1082 |
+
)
|
| 1083 |
+
raise
|
| 1084 |
system_prompt = augmented_system_prompt(system_prompt, plan_artifact)
|
| 1085 |
if not args.quiet:
|
| 1086 |
status = "ok" if plan_artifact.parsed_ok else "unstructured"
|
|
|
|
| 1095 |
if ctx_tools_enabled:
|
| 1096 |
system_prompt = _with_ctx_session_instructions(system_prompt, session_id)
|
| 1097 |
|
| 1098 |
+
try:
|
| 1099 |
+
mcp_configs = _apply_mcp_env_overlays(
|
| 1100 |
+
[_parse_mcp_spec(spec) for spec in args.mcp],
|
| 1101 |
+
args.mcp_env,
|
| 1102 |
+
)
|
| 1103 |
+
except Exception as exc:
|
| 1104 |
+
with telemetry_span():
|
| 1105 |
+
_record_cli_telemetry(
|
| 1106 |
+
"ctx.cli.run",
|
| 1107 |
+
session_id=session_id,
|
| 1108 |
+
phase="failed",
|
| 1109 |
+
payload=_run_setup_failure_payload(args, stage="validation"),
|
| 1110 |
+
outcome="error",
|
| 1111 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1112 |
+
error_kind=type(exc).__name__,
|
| 1113 |
+
exc=exc,
|
| 1114 |
+
)
|
| 1115 |
+
raise
|
| 1116 |
+
router = McpRouter(mcp_configs, session_id=session_id) if mcp_configs else None
|
| 1117 |
|
| 1118 |
# ctx-core tools.
|
| 1119 |
lifecycle = RuntimeLifecycleStore()
|
|
|
|
| 1144 |
"use --overwrite-session to replace it or ctx resume to continue it.",
|
| 1145 |
file=sys.stderr,
|
| 1146 |
)
|
| 1147 |
+
with telemetry_span():
|
| 1148 |
+
_record_cli_telemetry(
|
| 1149 |
+
"ctx.cli.run",
|
| 1150 |
+
session_id=session_id,
|
| 1151 |
+
phase="failed",
|
| 1152 |
+
payload=_run_setup_failure_payload(args, stage="session_create"),
|
| 1153 |
+
outcome="error",
|
| 1154 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1155 |
+
error_kind="FileExistsError",
|
| 1156 |
+
)
|
| 1157 |
return 1
|
| 1158 |
except ValueError as exc:
|
| 1159 |
print(f"error: {exc}", file=sys.stderr)
|
| 1160 |
+
with telemetry_span():
|
| 1161 |
+
_record_cli_telemetry(
|
| 1162 |
+
"ctx.cli.run",
|
| 1163 |
+
session_id=session_id,
|
| 1164 |
+
phase="failed",
|
| 1165 |
+
payload=_run_setup_failure_payload(args, stage="session_create"),
|
| 1166 |
+
outcome="error",
|
| 1167 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1168 |
+
error_kind=type(exc).__name__,
|
| 1169 |
+
)
|
| 1170 |
return 1
|
| 1171 |
+
with telemetry_span() as span:
|
| 1172 |
+
metadata = {
|
| 1173 |
+
"task": args.task,
|
| 1174 |
+
"model": args.model,
|
| 1175 |
+
"provider": args.provider or _model_provider_prefix(args.model),
|
| 1176 |
+
"provider_prefix": _model_provider_prefix(args.model),
|
| 1177 |
+
"api_key_env": api_key_env or "",
|
| 1178 |
+
"base_url": args.base_url or "",
|
| 1179 |
+
"system_prompt": system_prompt,
|
| 1180 |
+
"temperature": args.temperature,
|
| 1181 |
+
"max_tokens": args.max_tokens,
|
| 1182 |
+
"provider_timeout": args.provider_timeout,
|
| 1183 |
+
"max_iterations": args.max_iterations,
|
| 1184 |
+
"budget_usd": args.budget_usd,
|
| 1185 |
+
"budget_tokens": args.budget_tokens,
|
| 1186 |
+
"initial_trace_id": span.trace_id,
|
| 1187 |
+
"mcp": [
|
| 1188 |
+
{
|
| 1189 |
+
"name": c.name,
|
| 1190 |
+
"command": c.command,
|
| 1191 |
+
"args": list(c.args),
|
| 1192 |
+
"credential_env": list(c.credential_env),
|
| 1193 |
+
}
|
| 1194 |
+
for c in mcp_configs
|
| 1195 |
+
],
|
| 1196 |
+
"ctx_tools_enabled": ctx_tools_enabled,
|
| 1197 |
+
"tool_policy": {"allow": list(allow_tools), "deny": list(deny_tools)},
|
| 1198 |
+
"planner_used": plan_artifact is not None,
|
| 1199 |
+
"contract_used": bool(args.evaluator and args.contract),
|
| 1200 |
+
"evaluator_used": args.evaluator,
|
| 1201 |
+
"evaluator_max_rounds": args.evaluator_rounds if args.evaluator else None,
|
| 1202 |
+
"plan": plan_artifact.to_dict() if plan_artifact else None,
|
| 1203 |
+
"plan_usage": (
|
| 1204 |
+
{
|
| 1205 |
+
"input_tokens": plan_artifact.usage.input_tokens,
|
| 1206 |
+
"output_tokens": plan_artifact.usage.output_tokens,
|
| 1207 |
+
"cost_usd": plan_artifact.usage.cost_usd,
|
| 1208 |
+
}
|
| 1209 |
+
if plan_artifact
|
| 1210 |
+
else None
|
| 1211 |
+
),
|
| 1212 |
+
}
|
| 1213 |
+
observer = JsonlObserver(store, session_metadata=metadata)
|
| 1214 |
if ctx_tools_enabled:
|
| 1215 |
_record_lifecycle_safely(
|
| 1216 |
lifecycle,
|
|
|
|
| 1262 |
if args.contract and not args.planner:
|
| 1263 |
# Contracts refine planner output; without a plan
|
| 1264 |
# they'd have no prior spec to refine.
|
| 1265 |
+
_record_cli_telemetry(
|
| 1266 |
+
"ctx.cli.run",
|
| 1267 |
+
session_id=session_id,
|
| 1268 |
+
phase="failed",
|
| 1269 |
+
payload=_run_setup_failure_payload(
|
| 1270 |
+
args,
|
| 1271 |
+
stage="validation",
|
| 1272 |
+
),
|
| 1273 |
+
outcome="error",
|
| 1274 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1275 |
+
error_kind="SystemExit",
|
| 1276 |
+
)
|
| 1277 |
raise SystemExit(
|
| 1278 |
"error: --contract requires --planner (the contract "
|
| 1279 |
"refines the planner's success_criteria into "
|
|
|
|
| 1443 |
|
| 1444 |
|
| 1445 |
def _cmd_resume(args: argparse.Namespace) -> int:
|
| 1446 |
+
telemetry_started = time.perf_counter()
|
| 1447 |
sdir = Path(args.sessions_dir) if args.sessions_dir else default_sessions_dir()
|
| 1448 |
state = _load_session_for_cli(args.session_id, sdir)
|
| 1449 |
if state is None:
|
| 1450 |
+
with telemetry_span():
|
| 1451 |
+
_record_cli_telemetry(
|
| 1452 |
+
"ctx.cli.resume",
|
| 1453 |
+
session_id=args.session_id,
|
| 1454 |
+
phase="failed",
|
| 1455 |
+
payload=_resume_setup_failure_payload(
|
| 1456 |
+
args,
|
| 1457 |
+
stage="session_load",
|
| 1458 |
+
),
|
| 1459 |
+
outcome="error",
|
| 1460 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1461 |
+
error_kind="SessionLoadError",
|
| 1462 |
+
)
|
| 1463 |
return 1
|
|
|
|
| 1464 |
|
| 1465 |
meta = state.metadata
|
| 1466 |
+
previous_trace_id = _session_initial_trace_id(meta)
|
| 1467 |
model = args.model or meta.get("model")
|
| 1468 |
if not model:
|
| 1469 |
print(
|
| 1470 |
f"error: session {args.session_id!r} has no recorded model; pass --model explicitly.",
|
| 1471 |
file=sys.stderr,
|
| 1472 |
)
|
| 1473 |
+
with telemetry_span():
|
| 1474 |
+
_record_cli_telemetry(
|
| 1475 |
+
"ctx.cli.resume",
|
| 1476 |
+
session_id=args.session_id,
|
| 1477 |
+
phase="failed",
|
| 1478 |
+
payload=_resume_setup_failure_payload(
|
| 1479 |
+
args,
|
| 1480 |
+
stage="validation",
|
| 1481 |
+
previous_trace_id=previous_trace_id,
|
| 1482 |
+
),
|
| 1483 |
+
outcome="error",
|
| 1484 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1485 |
+
error_kind="ValueError",
|
| 1486 |
+
)
|
| 1487 |
return 1
|
| 1488 |
|
| 1489 |
use_ctx_tools = bool(meta.get("ctx_tools_enabled", True))
|
|
|
|
| 1519 |
timeout=provider_timeout,
|
| 1520 |
)
|
| 1521 |
|
| 1522 |
+
try:
|
| 1523 |
+
store = SessionStore.attach(args.session_id, sessions_dir=sdir)
|
| 1524 |
+
except (FileNotFoundError, OSError, ValueError) as exc:
|
| 1525 |
+
with telemetry_span():
|
| 1526 |
+
_record_cli_telemetry(
|
| 1527 |
+
"ctx.cli.resume",
|
| 1528 |
+
session_id=args.session_id,
|
| 1529 |
+
phase="failed",
|
| 1530 |
+
payload=_resume_setup_failure_payload(
|
| 1531 |
+
args,
|
| 1532 |
+
stage="session_attach",
|
| 1533 |
+
previous_trace_id=previous_trace_id,
|
| 1534 |
+
),
|
| 1535 |
+
outcome="error",
|
| 1536 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1537 |
+
error_kind=type(exc).__name__,
|
| 1538 |
+
exc=exc,
|
| 1539 |
+
)
|
| 1540 |
+
raise
|
| 1541 |
observer = JsonlObserver(
|
| 1542 |
store,
|
| 1543 |
session_metadata={},
|
|
|
|
| 1551 |
# transcript unless the user explicitly opts in for this resume.
|
| 1552 |
recorded_mcp_configs = _mcp_configs_from_metadata(meta)
|
| 1553 |
mcp_configs = recorded_mcp_configs if args.restore_session_mcp else []
|
| 1554 |
+
router = McpRouter(mcp_configs, session_id=args.session_id) if mcp_configs else None
|
| 1555 |
|
| 1556 |
lifecycle = RuntimeLifecycleStore()
|
| 1557 |
extra_tools: list[ToolDefinition] = []
|
|
|
|
| 1613 |
restored_mcp_count=len(mcp_configs),
|
| 1614 |
allow_count=len(allow_tools),
|
| 1615 |
deny_count=len(deny_tools),
|
| 1616 |
+
previous_trace_id=previous_trace_id,
|
| 1617 |
),
|
| 1618 |
outcome="ok",
|
| 1619 |
duration_ms=_duration_ms(telemetry_started),
|
|
|
|
| 1654 |
"ctx.cli.resume",
|
| 1655 |
session_id=args.session_id,
|
| 1656 |
phase="failed",
|
| 1657 |
+
payload=_with_previous_trace_id(
|
| 1658 |
+
_loop_result_payload(result),
|
| 1659 |
+
previous_trace_id,
|
| 1660 |
+
),
|
| 1661 |
outcome="error",
|
| 1662 |
duration_ms=_duration_ms(telemetry_started),
|
| 1663 |
error_kind=type(exc).__name__,
|
|
|
|
| 1681 |
"ctx.cli.resume",
|
| 1682 |
session_id=args.session_id,
|
| 1683 |
phase="finished",
|
| 1684 |
+
payload=_with_previous_trace_id(
|
| 1685 |
+
_loop_result_payload(result),
|
| 1686 |
+
previous_trace_id,
|
| 1687 |
+
),
|
| 1688 |
outcome=outcome,
|
| 1689 |
duration_ms=_duration_ms(telemetry_started),
|
| 1690 |
error_kind=error_kind,
|
src/ctx/dashboard_docs.py
CHANGED
|
@@ -572,6 +572,20 @@ def sanitize_docs_html(rendered_html: str) -> str:
|
|
| 572 |
return tag_html
|
| 573 |
return html.escape(tag_html)
|
| 574 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 575 |
for tag in dangerous_blocks:
|
| 576 |
rendered_html = re.sub(
|
| 577 |
rf"<\s*{tag}\b[^>]*>.*?<\s*/\s*{tag}\s*>",
|
|
@@ -608,8 +622,8 @@ def sanitize_docs_html(rendered_html: str) -> str:
|
|
| 608 |
flags=re.IGNORECASE,
|
| 609 |
)
|
| 610 |
rendered_html = re.sub(
|
| 611 |
-
r"\s+(href|src)\s*=\s*(
|
| 612 |
-
|
| 613 |
rendered_html,
|
| 614 |
flags=re.IGNORECASE,
|
| 615 |
)
|
|
|
|
| 572 |
return tag_html
|
| 573 |
return html.escape(tag_html)
|
| 574 |
|
| 575 |
+
def has_active_url_scheme(value: str) -> bool:
|
| 576 |
+
normalised = re.sub(r"[\x00-\x20\x7f]+", "", html.unescape(value)).lower()
|
| 577 |
+
return normalised.startswith(("javascript:", "data:text/html"))
|
| 578 |
+
|
| 579 |
+
def neutralise_active_url_attr(match: re.Match[str]) -> str:
|
| 580 |
+
attr_name = match.group(1)
|
| 581 |
+
raw_value = match.group(2)
|
| 582 |
+
value = raw_value.strip()
|
| 583 |
+
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
|
| 584 |
+
value = value[1:-1]
|
| 585 |
+
if has_active_url_scheme(value):
|
| 586 |
+
return f' {attr_name}="#"'
|
| 587 |
+
return match.group(0)
|
| 588 |
+
|
| 589 |
for tag in dangerous_blocks:
|
| 590 |
rendered_html = re.sub(
|
| 591 |
rf"<\s*{tag}\b[^>]*>.*?<\s*/\s*{tag}\s*>",
|
|
|
|
| 622 |
flags=re.IGNORECASE,
|
| 623 |
)
|
| 624 |
rendered_html = re.sub(
|
| 625 |
+
r"\s+(href|src|xlink:href|formaction)\s*=\s*(\"[^\"]*\"|'[^']*'|[^\s>]*)",
|
| 626 |
+
neutralise_active_url_attr,
|
| 627 |
rendered_html,
|
| 628 |
flags=re.IGNORECASE,
|
| 629 |
)
|
src/ctx/mcp_server/server.py
CHANGED
|
@@ -69,7 +69,13 @@ from typing import Any, BinaryIO
|
|
| 69 |
|
| 70 |
from ctx.adapters.generic.ctx_core_tools import CtxCoreToolbox
|
| 71 |
from ctx.adapters.generic.providers import ToolCall
|
| 72 |
-
from ctx.telemetry import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
|
| 75 |
_logger = logging.getLogger(__name__)
|
|
@@ -290,6 +296,39 @@ def _safe_mcp_payload(
|
|
| 290 |
return payload
|
| 291 |
|
| 292 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
def _mcp_result_payload(method: str, result: dict[str, Any]) -> dict[str, Any]:
|
| 294 |
payload: dict[str, Any] = {}
|
| 295 |
if method == "tools/list":
|
|
@@ -464,6 +503,8 @@ def _process_line(
|
|
| 464 |
response_emitted=not is_notification,
|
| 465 |
request_id_type=_request_id_type(frame),
|
| 466 |
)
|
|
|
|
|
|
|
| 467 |
|
| 468 |
if not isinstance(method, str) or not method:
|
| 469 |
if not is_notification:
|
|
@@ -481,7 +522,7 @@ def _process_line(
|
|
| 481 |
)
|
| 482 |
return
|
| 483 |
|
| 484 |
-
with telemetry_span():
|
| 485 |
if is_notification:
|
| 486 |
# Per spec we accept (and ignore) unknown notifications rather
|
| 487 |
# than erroring — it lets hosts send progress/ping/cancel
|
|
|
|
| 69 |
|
| 70 |
from ctx.adapters.generic.ctx_core_tools import CtxCoreToolbox
|
| 71 |
from ctx.adapters.generic.providers import ToolCall
|
| 72 |
+
from ctx.telemetry import (
|
| 73 |
+
hash_identifier,
|
| 74 |
+
parse_traceparent,
|
| 75 |
+
record_event,
|
| 76 |
+
record_exception,
|
| 77 |
+
telemetry_span,
|
| 78 |
+
)
|
| 79 |
|
| 80 |
|
| 81 |
_logger = logging.getLogger(__name__)
|
|
|
|
| 296 |
return payload
|
| 297 |
|
| 298 |
|
| 299 |
+
def _jsonrpc_metadata(frame: dict[str, Any], params: object) -> dict[str, Any]:
|
| 300 |
+
metadata: dict[str, Any] = {}
|
| 301 |
+
for value in (frame.get("metadata"), frame.get("_meta")):
|
| 302 |
+
if isinstance(value, dict):
|
| 303 |
+
metadata.update(value)
|
| 304 |
+
if isinstance(params, dict) and isinstance(params.get("_meta"), dict):
|
| 305 |
+
metadata.update(params["_meta"])
|
| 306 |
+
return metadata
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def _trace_context_from_metadata(
|
| 310 |
+
frame: dict[str, Any],
|
| 311 |
+
params: object,
|
| 312 |
+
) -> tuple[str | None, str | None]:
|
| 313 |
+
metadata = _jsonrpc_metadata(frame, params)
|
| 314 |
+
raw_traceparent = metadata.get("traceparent")
|
| 315 |
+
parsed = parse_traceparent(raw_traceparent) if isinstance(raw_traceparent, str) else None
|
| 316 |
+
if parsed is None:
|
| 317 |
+
return None, None
|
| 318 |
+
return parsed
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def _safe_metadata_payload(frame: dict[str, Any], params: object) -> dict[str, Any]:
|
| 322 |
+
metadata = _jsonrpc_metadata(frame, params)
|
| 323 |
+
payload: dict[str, Any] = {}
|
| 324 |
+
if isinstance(metadata.get("traceparent"), str):
|
| 325 |
+
payload["ctx.traceparent.received"] = parse_traceparent(metadata["traceparent"]) is not None
|
| 326 |
+
session_hash = metadata.get("ctx.session.hash")
|
| 327 |
+
if isinstance(session_hash, str) and session_hash.startswith("sha256:"):
|
| 328 |
+
payload["ctx.session.hash"] = session_hash
|
| 329 |
+
return payload
|
| 330 |
+
|
| 331 |
+
|
| 332 |
def _mcp_result_payload(method: str, result: dict[str, Any]) -> dict[str, Any]:
|
| 333 |
payload: dict[str, Any] = {}
|
| 334 |
if method == "tools/list":
|
|
|
|
| 503 |
response_emitted=not is_notification,
|
| 504 |
request_id_type=_request_id_type(frame),
|
| 505 |
)
|
| 506 |
+
base_payload.update(_safe_metadata_payload(frame, params))
|
| 507 |
+
trace_id, parent_span_id = _trace_context_from_metadata(frame, params)
|
| 508 |
|
| 509 |
if not isinstance(method, str) or not method:
|
| 510 |
if not is_notification:
|
|
|
|
| 522 |
)
|
| 523 |
return
|
| 524 |
|
| 525 |
+
with telemetry_span(trace_id=trace_id, parent_span_id=parent_span_id):
|
| 526 |
if is_notification:
|
| 527 |
# Per spec we accept (and ignore) unknown notifications rather
|
| 528 |
# than erroring — it lets hosts send progress/ping/cancel
|
src/ctx/monitor/api/readonly.py
CHANGED
|
@@ -109,7 +109,7 @@ def handle_readonly_route(
|
|
| 109 |
slug = params["slug"]
|
| 110 |
sidecar = deps.load_sidecar(slug, query.get("type"))
|
| 111 |
if sidecar is None:
|
| 112 |
-
return ReadOnlyApiResponse(
|
| 113 |
return ReadOnlyApiResponse(sidecar)
|
| 114 |
if name == "api_graph":
|
| 115 |
slug = params["slug"]
|
|
|
|
| 109 |
slug = params["slug"]
|
| 110 |
sidecar = deps.load_sidecar(slug, query.get("type"))
|
| 111 |
if sidecar is None:
|
| 112 |
+
return ReadOnlyApiResponse({"detail": f"no sidecar for {slug}"}, status=404)
|
| 113 |
return ReadOnlyApiResponse(sidecar)
|
| 114 |
if name == "api_graph":
|
| 115 |
slug = params["slug"]
|
src/ctx/telemetry/__init__.py
CHANGED
|
@@ -439,19 +439,58 @@ def current_telemetry_span() -> TelemetrySpan | None:
|
|
| 439 |
return _CURRENT_SPAN.get()
|
| 440 |
|
| 441 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
@contextmanager
|
| 443 |
def telemetry_span(
|
| 444 |
*,
|
| 445 |
trace_id: str | None = None,
|
| 446 |
span_id: str | None = None,
|
|
|
|
| 447 |
) -> Iterator[TelemetrySpan]:
|
| 448 |
-
"""Start a
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 449 |
|
| 450 |
parent = _CURRENT_SPAN.get()
|
| 451 |
span = TelemetrySpan(
|
| 452 |
trace_id=trace_id or (parent.trace_id if parent is not None else uuid.uuid4().hex),
|
| 453 |
span_id=span_id or secrets.token_hex(8),
|
| 454 |
-
parent_span_id=parent.span_id if parent is not None else
|
| 455 |
)
|
| 456 |
token = _CURRENT_SPAN.set(span)
|
| 457 |
try:
|
|
|
|
| 439 |
return _CURRENT_SPAN.get()
|
| 440 |
|
| 441 |
|
| 442 |
+
def _valid_trace_id(value: str) -> bool:
|
| 443 |
+
return len(value) == 32 and value != "0" * 32 and all(ch in "0123456789abcdef" for ch in value)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def _valid_span_id(value: str) -> bool:
|
| 447 |
+
return len(value) == 16 and value != "0" * 16 and all(ch in "0123456789abcdef" for ch in value)
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def traceparent_from_span(span: TelemetrySpan | None = None) -> str | None:
|
| 451 |
+
"""Return a W3C traceparent header for ``span`` or the active span."""
|
| 452 |
+
|
| 453 |
+
resolved = span if span is not None else _CURRENT_SPAN.get()
|
| 454 |
+
if resolved is None:
|
| 455 |
+
return None
|
| 456 |
+
if not _valid_trace_id(resolved.trace_id) or not _valid_span_id(resolved.span_id):
|
| 457 |
+
return None
|
| 458 |
+
return f"00-{resolved.trace_id}-{resolved.span_id}-01"
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def parse_traceparent(value: str) -> tuple[str, str] | None:
|
| 462 |
+
"""Parse W3C traceparent into ``(trace_id, parent_span_id)``."""
|
| 463 |
+
|
| 464 |
+
parts = value.strip().split("-")
|
| 465 |
+
if len(parts) != 4:
|
| 466 |
+
return None
|
| 467 |
+
version, trace_id, span_id, flags = parts
|
| 468 |
+
if version != "00" or len(flags) != 2:
|
| 469 |
+
return None
|
| 470 |
+
if not _valid_trace_id(trace_id) or not _valid_span_id(span_id):
|
| 471 |
+
return None
|
| 472 |
+
return trace_id, span_id
|
| 473 |
+
|
| 474 |
+
|
| 475 |
@contextmanager
|
| 476 |
def telemetry_span(
|
| 477 |
*,
|
| 478 |
trace_id: str | None = None,
|
| 479 |
span_id: str | None = None,
|
| 480 |
+
parent_span_id: str | None = None,
|
| 481 |
) -> Iterator[TelemetrySpan]:
|
| 482 |
+
"""Start a telemetry span using OpenTelemetry-compatible IDs.
|
| 483 |
+
|
| 484 |
+
An active span is always the parent. ``parent_span_id`` is used only when
|
| 485 |
+
importing an external trace, such as MCP ``traceparent`` metadata, with no
|
| 486 |
+
active local span.
|
| 487 |
+
"""
|
| 488 |
|
| 489 |
parent = _CURRENT_SPAN.get()
|
| 490 |
span = TelemetrySpan(
|
| 491 |
trace_id=trace_id or (parent.trace_id if parent is not None else uuid.uuid4().hex),
|
| 492 |
span_id=span_id or secrets.token_hex(8),
|
| 493 |
+
parent_span_id=parent.span_id if parent is not None else parent_span_id,
|
| 494 |
)
|
| 495 |
token = _CURRENT_SPAN.set(span)
|
| 496 |
try:
|