Skip to content

feat(mcp): add KHI Model Context Protocol server for agentic cluster investigation - #1177

Merged
kyasbal merged 40 commits into
mainfrom
epic/mcp
Oct 26, 2026
Merged

kyasbal merged 40 commits into
mainfrom
epic/mcp

Conversation

@kyasbal

@kyasbal kyasbal commented Oct 26, 2026

Copy link
Copy Markdown
Member

Part of #1049
Closes #1134

Background

KHI collects, correlates, and structures Kubernetes and Google Cloud logs into hierarchical resource timelines, revision manifests, and CEL-filterable workbench indexes, but previously exposed these capabilities only through its interactive browser UI and frontend-oriented RPC endpoints. AI troubleshooting agents investigating cluster incidents had to query raw logs without KHI's resource grouping, inferred revision diffs, or timeline correlation, and had no direct way to share reproducible filter views back to engineers in the KHI Web UI.

Approach

Integrates a stateless Model Context Protocol (MCP) server into the KHI HTTP server (/mcp Streamable HTTP and /mcp/sse SSE transports, automatically skipped in one-shot job mode), returning token-efficient Markdown rendered from embedded templates across four subsystems:

  1. Inspection Lifecycle, Summary Metadata & File Upload:

    • Exposes uniquely addressable inspection catalogs and summaries as MCP resources (khi://inspection-types, khi://inspections, khi://inspections/{id}) and models parameterized lifecycle operations as stateless tools keyed by inspectionId (create_inspection, update_inspection_features, dry_run_inspection, request_file_upload, run_inspection, wait_inspection, cancel_inspection).
    • Records per-feature query log counts, core cluster labels, and v6 .khi filter vocabulary metadata (path keys, timelineType examples, and logType values) so both live runs and imported .khi files immediately advertise valid CEL filter values in the inspection summary.
    • Distinguishes defaulted from caller-supplied form parameters during dry_run_inspection, pins resolved defaults when starting run_inspection, translates missing or expired Google Cloud credentials into actionable GOOGLE_CLOUD_AUTH guidance, and issues bounded upload URLs for file-based inspection types.
  2. Shared Workbench Search, Resource History & Report Validation:

    • Manages shared in-memory workbenches per inspection ID with non-blocking on-demand loading (WORKBENCH_LOADING status while indexing) and idle eviction.
    • Provides CEL-filtered timeline hierarchy search (search_timelines), cross-timeline log search (search_logs), per-timeline log listings (get_timeline_logs), path-targeted log body inspection (get_log), and resource revision history, manifests, and unified diffs (get_resource_revisions, get_resource_manifest, get_resource_diff), returning copy-pasteable Applied filter blocks that reproduce the same view in the Web UI.
    • Adds validate_report with rule-based verification of cited log IDs against the loaded inspection to catch invalid references before agents finalize reports.
  3. Headless Timeline Screenshot Rendering:

    • Adds a dedicated Angular render route (/render/:inspectionId) that renders filtered timelines without chrome overlays and exposes deterministic readiness synchronization once layout and WebGL drawing settle.
    • Drives an on-demand headless Chrome/Chromium process over Chrome DevTools Protocol (render_timelines, configurable via --mcp-disable-render-tool) to capture PNG timeline screenshots for multimodal investigation, paired with a multi-target Dockerfile bundling headless Chromium.
  4. Static CEL Reference Documentation:

    • Includes static CEL timeline and log filter references under plugins/khi/skills/khi-investigation/references/ paired with the dynamic Filter vocabulary output.

Follow-ups

… templates (#1038) (#1057)

* feat(mcp): add MCP server foundation with HTTP transport and Markdown templates (#1038)

* fix(mcp): use constants.VERSION for MCP server implementation version
* feat(mcp): add inspection list and AI summary resources (#1039)

* refactor(inspection): rename pkg/core/inspection/ai to pkg/core/inspection/summary

* refactor(task,summary): add coretask.WithTitle/WithDescription and fail fast on invalid summary calls
…1067)

* feat(mcp): add dry_run_inspection and run_inspection tools (#1040)

* refactor(mcp): simplify convertMCPParameters to accept string, bool, and string arrays

* refactor(mcp): remove redundant TaskInputKeyTimezoneShiftHours deletion
… demand (#1041) (#1072)

* feat(workbench): share workbenches by inspection ID and evict only on demand (#1041)

* fix(workbench): clear removed subscriber reference when unsubscribing

* test(workbench): remove redundant workbenchID variable assignments
…1081)

* feat(workbench): add CEL reference documentation generator (#1042)

* fix(workbench): remove redundant nil checks before protobuf getters in reference.go

* refactor(workbench): use text/template for CEL reference generation
…1082)

* feat(workbench): add filter and timeline read layer for MCP (#1042)

* fix(workbench): escape non-identifier keys in BuildTimelineQuery
…lpers (#1042) (#1083)

* feat(mcp): add timelinePath, appliedFilter, and CEL error template helpers (#1042)

* refactor(mcp): use embedded template for FormatAppliedFilter
…#1089)

* feat(workbench): add SearchTimelines tree aggregation for MCP (#1043)

* perf(workbench): iterate matched bitmap and cache default timeline types (#1043)

* fix(workbench): count all severities by style definition in SearchTimelines (#1043)

Resolve each matched log to its severity definition in the style chunk instead of comparing raw integer severities, and remove the integer Severity fields of cel.EventInfo and cel.RevisionInfo that no longer have readers.

* refactor(workbench): build severity and timeline type maps once at workbench load (#1043)

The style chunk does not change while the workbench is open, so SearchTimelines no longer rebuilds the severity map and the timeline type description map from it on every call. buildStyleMaps builds both maps once when BuildBaseSearchIndex runs at load, and SearchTimelines reuses them through Workbench.styles.

* fix(workbench): deduplicate logs across descendants when aggregating severity counts (#1043)
…1043) (#1090)

* feat(workbench): add SearchLogs cross-timeline aggregation for MCP (#1043)

* refactor(workbench): use time.Time.Compare in buildSortedTimelineGroups (#1043)

* fix(workbench): count log severities by style definition in SearchLogs (#1043)

Resolve each matched log to its severity definition in the style chunk instead of mapping integer severity orders to hardcoded labels, and drop the removed integer Severity field from the test fixtures.

* refactor(workbench): reuse the severity map built at workbench load in SearchLogs (#1043)

SearchLogs no longer rebuilds the severity map from the style chunk on every call. It looks up severity definitions in the map that buildStyleMaps builds once when the workbench loads.

* fix(workbench): sample logs evenly across time range in SearchLogs (#1043)
* feat(mcp): add search_timelines and search_logs tools (#1043)

* fix(mcp): render all severity counts in search tools (#1043)

* fix(mcp): replace broken CEL resource references in tool descriptions (#1043)
fix(workbench): treat missing CEL path levels as empty strings instead of aborting the timeline filter (#1123)

* fix(workbench): treat missing CEL path levels as empty strings instead of aborting the timeline filter

* fix(workbench): reject non-string keys in CEL path lookups instead of resolving them to empty strings

* fix(workbench): make CEL path equality reflexive by unwrapping pathMap operands

* test(workbench): cover timelines without a path level that still match the CEL filter
…ead methods (#1044) (#1128)

* feat(workbench): add body truncation, timeline logs, and log detail read methods (#1044)

* fix(workbench): drop test-only limits, defensive checks, and duplicate truncation marker in timeline log reads (#1044)

* fix(workbench): drop unreachable linked timeline check in GetLogDetail (#1044)

* refactor(workbench): derive chunk truncation, embed linked timeline, and share index helpers in timeline log reads (#1044)

* test(workbench): cover rune-boundary and invalid UTF-8 cuts in the body round-trip test (#1044)
…ds (#1044) (#1129)

* feat(workbench): add resource revision, manifest, and diff read methods (#1044)

* fix(workbench): use the fixed body limit and drop defensive checks in resource history reads (#1044)

* refactor(workbench): adopt shared index helpers and BodyChunk, clarify range names, and extend resource history tests (#1044)

* refactor(workbench): name the matched revision count matchedCount in GetResourceRevisions (#1044)

* refactor(workbench): make RevisionSelector unable to hold an invalid state via RevisionAtIndex and RevisionAtTime (#1044, #1127)
…#1044) (#1130)

* feat(mcp): add get_timeline_logs, get_log, and resource history tools (#1044)

* fix(mcp): validate byteOffset, drop duplicate truncation marker, and clarify revision window header (#1044)

* refactor(mcp): adopt BodyChunk and OtherTimeline, validate byteOffset upper bound, split format helpers, and extend template tests (#1044)

* refactor(mcp): separate other timeline template data, skip unused diff rendering, and neutralize the byteOffset range message (#1044)

* refactor(mcp): build the manifest revision selector with RevisionAtIndex and RevisionAtTime (#1044, #1127)
#1047) (#1131)

* feat(upload): add single-PUT upload URLs for file form fields (#1047)

* feat(mcp): support file input inspection types via request_file_upload (#1047)

* fix(uploadurl): record the failure when an upload session cannot start (#1047)

* refactor(uploadurl): name the upload URL token urlToken to distinguish it from upload tokens (#1047)

* fix(upload): roll back the upload status when a chunk session cannot start (#1047)

* feat(uploadurl): accept a single upload per upload URL (#1047)

* refactor(uploadurl): export StatusProcessing and reuse it for the MCP upload status

* refactor(mcp,uploadurl): rename Upload to UploadStatus, uploadURLs to uploadURLIssuer, and targets to targetsByURLToken

* refactor(mcp): look up the upload token from the form fields instead of the render model

* test(upload,mcp): cover the upload URL route, unexpired URL tokens, recovery after a verification error, and empty groups

* refactor(uploadurl): claim an upload URL in one locked step after the size checks

* docs(uploadurl): describe StatusProcessing as covering both storing and verifying

* refactor(mcp): rename dry run locals and the render model field for clarity

* test(uploadurl): assert the first upload status in the single-use URL test

* refactor(uploadurl): check the claim error with err != nil before choosing the status
…alues fails in Run (#1142)

* fix(inspection): prevent runner state corruption when withRunContextValues fails in Run

* fix(inspection): close builder file writer when run context setup or execution fails

* refactor(inspection): use context.AfterFunc for run context resource cleanup
…ord fetched log counts (#1120) (#1144)

* fix(gcpcommon): resolve query resource name defaults before reading and sync form metadata

* fix(summary,mcp): record and display fetched log counts per executed query

* test(metadata,gcpcommon): add unit tests for UpdateGroupChildTextFieldDefault and query LogCount
…and wait timeout (#1134) (#1143)

* fix(mcp): show and pin the default values that dry runs fill in

* fix(mcp): explain how to pass each field type and report non-array set values as field errors

* fix(mcp): keep wait_inspection below the tool call timeout of MCP clients

* fix(mcp): render applied filter queries as YAML literal blocks

* feat(mcp): add server instructions and a filter vocabulary section

* fix(mcp): use an explicit indentation indicator for tab-led filter queries

* fix(mcp): refine filter vocabulary, CEL body() guidance, wait timeout, and #1134 review items

* style(mcp): format inspection_run.go with goimports
…clarify @Managed namespace default (#1145)

* fix(mcp): compact dry_run_inspection output and split inspection_form.go

* fix(mcp,k8scontainer): keep field descriptions in dry_run_inspection and clarify @Managed namespace default

* test(mcp): update logFileDryRunText in inspection_upload_test.go to keep description
…rch_timelines match counts (#1146)

* fix(mcp): report revisions, manifests, and diffs without a recorded body

* fix(mcp): distinguish direct timeline matches from ancestor nodes in search_timelines

* feat(mcp,workbench): omit metadata.managedFields by default in get_resource_manifest

* test(workbench): fix expected YAML in TestGetResourceManifest_IncludeManagedFields

* test(workbench): simplify TestSearchTimelines assertions with cmp.Diff
…Id) for screenshot capture (#1149)

* feat(web,server): add timeline-only render route (/render/:inspectionId) for screenshot capture

* refactor(web): move timeline renderer bridge types to common/schema

* refactor(web): namespace timeline renderer under window.__khiCDPBridge.timelineRenderer

* fix(web): setup GLContextManager before registering render loop handler
…-target Dockerfile (#1154)

* feat(cdp,docker): add headless Chrome CDP browser lifecycle and multi-target Dockerfile

* fix(cdp): synchronize Client.Call and Client.Close with a mutex

* refactor(cdp): encapsulate raw CDP calls behind high-level Client methods
…derer (#1150)

* feat(mcp): add render_timelines MCP tool with headless Chrome CDP renderer

* refactor(mcp): invoke window.__khiCDPBridge.timelineRenderer from CDP renderer

* fix(mcp): fail fast on CDP transport errors during render page navigation

* refactor(mcp): use shared cdp.Browser in ChromeTimelineImageRenderer and conditionally register render_timelines

* refactor(mcp): use high-level cdp.Client methods in ChromeTimelineImageRenderer

* test(mcp): simplify handleRenderTimelines test assertions using cmp.Diff on CallToolResult
* fix(workbench): treat missing CEL path levels as empty strings instead of aborting the timeline filter (#1123)

* fix(workbench): treat missing CEL path levels as empty strings instead of aborting the timeline filter

* fix(workbench): reject non-string keys in CEL path lookups instead of resolving them to empty strings

* fix(workbench): make CEL path equality reflexive by unwrapping pathMap operands

* test(workbench): cover timelines without a path level that still match the CEL filter

* feat(k8saudit): resolve undetermined resource names from request/response metadata and generateName (#1148)

* feat(k8saudit): resolve undetermined resource names from request/response metadata and generateName

* fix(k8saudit): fall back to response metadata.generateName and simplify Status kind check

* refactor(k8saudit): rename primaryName to nameFromLogFields and only read metadata.name from response

* revert(k8saudit): revert unnecessary changes in mapper_error.go

* build(deps): update npm dependencies to supersede Dependabot PRs (#1155)

Update root, web/, and scripts/msdf-generator/ npm dependencies to consolidate
and supersede the 11 open Dependabot PRs on GitHub:
- #1152: follow-redirects (1.16.0 -> 1.16.1 in /web)
- #1151: hono (4.13.7 -> 4.13.13 in /web)
- #1147: @angular/router (21.2.22 -> 21.2.25 in /web, along with peer @angular/* packages)
- #1141: brace-expansion (1.1.18 -> 1.1.21, 5.0.9 -> 5.0.12 in /web)
- #1140: handlebars (4.7.9 -> 4.7.10 in /web)
- #1139: handlebars (4.7.9 -> 4.7.10 in /scripts/msdf-generator)
- #1138: source-map-js (1.2.1 -> 1.2.2 in /web)
- #1137: proxy-addr (2.0.7 -> 2.0.8 in /web)
- #1135: serialize-javascript (7.1.1 -> 7.1.2 in /web)
- #1117: markdown-it (14.3.0 -> 15.0.1) and markdownlint-cli2 (0.23.2 -> 0.23.3)
- #1062: js-yaml (5.2.2 -> 5.4.1) and markdownlint-cli2 (0.23.2 -> 0.23.3)

* build(deps): update Go to 1.27.3, Node.js to 26.12.1, and golangci-lint to v2.15.0 (#1159)

* build(deps): update Go to 1.27.3, Node.js to 26.12.1, and golangci-lint to v2.15.0

* fix(make): add container fallback to format-go when GOLANGCILINT_CMD is empty

* chore(agent): remove requirement for user approval before push (#1160)
… files (#1165)

* refactor(mcp,workbench): simplify CEL references to static files and update serverInstructions

* feat(khifile,inspection): record filter vocabulary metadata in KHI v6 files

* style(khifile): use cmp.Compare for timeline type label tie-breaking

* test(inspectioncore): use protocmp.Transform to compare FilterVocabularyMetadata proto
… setup (#1166)

* test(workbench): simplify workbench tests and share inspection server setup

* test(workbench): use struct for want values in table tests
* feat(mcp): include Filter vocabulary in inspection summary

* docs(mcp): use singular kind in cel-timeline examples and realistic logType labels in golden test

* docs(mcp): unify timeline path syntax on path["<key>"]
* test(core,server): simplify core, server, and task unit tests

* test(init): specify expected MCP and render tool state in test cases
* test(web): simplify timeline render and workbench client specs

* test(web): fix failing Angular specs in timeline frame and render smart tests

* test(web): stub GLContextManager setup in timeline frame spec to prevent WebGL context leak
@kyasbal
kyasbal requested review from RyuSA and jyane as code owners October 26, 2026 03:06
@kyasbal kyasbal added type:feature New feature or request area:backend-core Core backend frameworks, DAG task runner, and server API labels Oct 26, 2026
@kyasbal
kyasbal requested a review from kkuchima as a code owner October 26, 2026 03:06
@kyasbal kyasbal added area:backend-parser Log parsers and log timeline mapper tasks area:frontend Web frontend application and UI components labels Oct 26, 2026
@kyasbal
kyasbal requested a review from renamoo as a code owner October 26, 2026 03:06
@kyasbal kyasbal added area:cicd GitHub Actions workflows and release pipelines area:khifile .khi file format, serialization, and schema labels Oct 26, 2026
@kyasbal
kyasbal requested a review from K53 as a code owner October 26, 2026 03:06
@kyasbal kyasbal added the area:agent AI agent skills, rules, and prompt workflows label Oct 26, 2026
@kyasbal
kyasbal enabled auto-merge October 26, 2026 03:07

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements a Model Context Protocol (MCP) server for the KHI service, allowing AI agents to perform inspections, search logs, and render timelines. The changes include adding MCP tool handlers, a summary collection framework, a headless Chrome renderer for timeline images, and updated workbench management to support shared sessions and eviction. Additionally, the Go version was upgraded to 1.27.3, and CEL evaluation was improved with path-level support and type validation. The reviewer correctly identified a race condition in the InspectionTaskRunner cleanup logic, suggesting a synchronous cleanup approach to ensure thread safety.

Comment on lines +185 to +190
context.AfterFunc(ctx, func() {
builder.Dispose()
if closer != nil {
_ = closer.Close()
}
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using context.AfterFunc to clean up the builder and closer asynchronously introduces a potential race condition. If the context is cancelled (e.g., due to user cancellation or a timeout) while tasks inside runFunc are still active and writing to the builder or writer, builder.Dispose() and closer.Close() will execute concurrently. This can lead to write-after-close races or panics.

To ensure thread safety, please perform the builder and closer cleanup synchronously after runFunc has completely returned, rather than relying on the asynchronous context.AfterFunc callback.

@kyasbal
kyasbal added this pull request to the merge queue Oct 26, 2026
Merged via the queue into main with commit 18f6682 Oct 26, 2026
20 of 21 checks passed
@kyasbal
kyasbal deleted the epic/mcp branch October 26, 2026 03:23
@kyasbal kyasbal mentioned this pull request Nov 11, 2026
16 of 23 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent AI agent skills, rules, and prompt workflows area:backend-core Core backend frameworks, DAG task runner, and server API area:backend-parser Log parsers and log timeline mapper tasks area:cicd GitHub Actions workflows and release pipelines area:frontend Web frontend application and UI components area:khifile .khi file format, serialization, and schema type:feature New feature or request

1 participant