diff --git a/.bestpractices.json b/.bestpractices.json index 7294d39..3e00497 100644 --- a/.bestpractices.json +++ b/.bestpractices.json @@ -62,11 +62,11 @@ "vulnerability_report_response_status": "N/A", "vulnerability_report_response_justification": "The maintainer confirmed on 2026-09-05 that no private vulnerability reports were received in the preceding six months; the project advisory list was also empty. The policy requires acknowledgment within 14 days for future reports. https://github.com/lennrt/tempestkeep/blob/main/SECURITY.md https://github.com/lennrt/tempestkeep/blob/main/docs/openssf.md", "build_status": "Met", - "build_justification": "The source builds with Go 1.27.0 and make using CGO_ENABLED=0. Go and make are FLOSS; no proprietary build tool is required. https://github.com/lennrt/tempestkeep/blob/main/Makefile https://github.com/lennrt/tempestkeep/blob/main/README.md", + "build_justification": "The source builds with Go 1.27.2 and make using CGO_ENABLED=0. Go and make are FLOSS; no proprietary build tool is required. https://github.com/lennrt/tempestkeep/blob/main/Makefile https://github.com/lennrt/tempestkeep/blob/main/README.md", "build_common_tools_status": "Met", - "build_common_tools_justification": "The source builds with Go 1.27.0 and make using CGO_ENABLED=0. Go and make are FLOSS; no proprietary build tool is required. https://github.com/lennrt/tempestkeep/blob/main/Makefile https://github.com/lennrt/tempestkeep/blob/main/README.md", + "build_common_tools_justification": "The source builds with Go 1.27.2 and make using CGO_ENABLED=0. Go and make are FLOSS; no proprietary build tool is required. https://github.com/lennrt/tempestkeep/blob/main/Makefile https://github.com/lennrt/tempestkeep/blob/main/README.md", "build_floss_tools_status": "Met", - "build_floss_tools_justification": "The source builds with Go 1.27.0 and make using CGO_ENABLED=0. Go and make are FLOSS; no proprietary build tool is required. https://github.com/lennrt/tempestkeep/blob/main/Makefile https://github.com/lennrt/tempestkeep/blob/main/README.md", + "build_floss_tools_justification": "The source builds with Go 1.27.2 and make using CGO_ENABLED=0. Go and make are FLOSS; no proprietary build tool is required. https://github.com/lennrt/tempestkeep/blob/main/Makefile https://github.com/lennrt/tempestkeep/blob/main/README.md", "test_status": "Met", "test_justification": "The MIT-licensed Go test suite runs with make test or go test ./... -count=1 -timeout=5m, and in GitHub CI. https://github.com/lennrt/tempestkeep/blob/main/Makefile https://github.com/lennrt/tempestkeep/blob/main/CONTRIBUTING.md", "test_invocation_status": "Met", diff --git a/.gitattributes b/.gitattributes index 5746687..2194546 100644 --- a/.gitattributes +++ b/.gitattributes @@ -10,6 +10,11 @@ *.yml text eol=lf *.txt text eol=lf *.tape text eol=lf +*.js text eol=lf +*.mjs text eol=lf +*.css text eol=lf +*.html text eol=lf +internal/mcpapp/ui/app.html linguist-generated=true .env.example text eol=lf Makefile text eol=lf go.mod text eol=lf diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 536aeb9..b471478 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -21,7 +21,7 @@ body: attributes: label: Environment description: Include the operating system, architecture, and `go version` when relevant. - placeholder: macOS arm64; go version go1.27.0 darwin/arm64 + placeholder: macOS arm64; go version go1.27.2 darwin/arm64 validations: required: true - type: textarea diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 00042c6..b13b581 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,6 +35,30 @@ jobs: - name: Validate specifications and active changes run: npm run spec:check + mcp-apps: + name: MCP Apps browser checks + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: "24.19.0" + cache: npm + + - name: Install locked development tools + run: npm ci --ignore-scripts --no-audit --no-fund + + - name: Check the embedded app matches its source + run: npm run app:check + + - name: Install Chromium + run: npx playwright install --with-deps chromium + + - name: Test the sandboxed app with the official host bridge + run: npm run app:test + platforms: name: Native tests (${{ matrix.os }}) strategy: @@ -50,7 +74,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.0" + go-version: "1.27.2" check-latest: false cache: true @@ -64,7 +88,7 @@ jobs: run: go build ./... verify: - name: Go 1.27.0 verification + name: Go 1.27.2 verification runs-on: ubuntu-latest timeout-minutes: 25 steps: @@ -72,7 +96,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.0" + go-version: "1.27.2" check-latest: false cache: true @@ -106,7 +130,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.0" + go-version: "1.27.2" check-latest: false cache: true @@ -123,7 +147,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.0" + go-version: "1.27.2" check-latest: false cache: true @@ -147,7 +171,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.0" + go-version: "1.27.2" check-latest: false cache: true diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 781a672..e8ba6de 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -23,7 +23,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.0" + go-version: "1.27.2" check-latest: false cache: true diff --git a/.github/workflows/demo.yml b/.github/workflows/demo.yml index 5e90cbe..e41d590 100644 --- a/.github/workflows/demo.yml +++ b/.github/workflows/demo.yml @@ -19,7 +19,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.0" + go-version: "1.27.2" check-latest: false cache: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 194d990..e4e718e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -21,7 +21,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.0" + go-version: "1.27.2" check-latest: false cache: true diff --git a/.gitignore b/.gitignore index b8b0d9b..64fbaae 100644 --- a/.gitignore +++ b/.gitignore @@ -15,8 +15,9 @@ /coverage.out /scorecard-results.sarif -# Development-only OpenSpec dependencies +# Development-only specification and MCP Apps tooling /node_modules/ +/dist/playwright/ # OS .DS_Store diff --git a/.golangci.yml b/.golangci.yml index c688f8c..39f3c3a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,4 +1,4 @@ -# golangci-lint v2.13.2 configuration. +# golangci-lint v2.14.0 configuration. version: "2" run: diff --git a/CHANGELOG.md b/CHANGELOG.md index bd847e1..17d7372 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,43 @@ # Changelog +## 0.3.0 (proposed, unreleased) + +### Added + +- MCP Apps views for available read-only weather and archive tools, embedded in + the Go binary and rendered by supporting MCP hosts. +- Weather charts and searchable, sortable, paginated tables with host themes + and refresh through the same read-only tool. +- Self-contained app resources with no external network origins or device + permissions. API credentials remain in the Go server. +- Protocol and Playwright browser coverage, plus reproducible screenshots from + a synthetic MCP Apps test host. +- MCP Apps setup, compatibility, privacy, architecture, and OpenSpec requirements. + +### Changed + +- Pin Go 1.27.2 for module builds, repository checks, CI, and release qualification. + Contributors must use the updated patch toolchain. See + [ADR 0007](docs/adr/0007-go-patch-toolchain.md). +- Update the pinned golangci-lint to v2.14.0 so static analysis can read the + patched toolchain's compiler export data. + +### Compatibility + +MCP Apps is additive. Hosts that advertise support receive UI resource metadata +on read-only tools. Ordinary clients retain the existing tools and results. +Resource discovery gains HTML resources. Existing tool schemas, annotations, +result shapes, archive formats, and configuration remain unchanged. + +The app's refresh action does not collect history or mutate the archive. +Frontend development uses pinned npm dependencies. The Go build and runtime do +not require Node.js. Existing archives need no migration. See +[ADR 0006](docs/adr/0006-mcp-apps.md) for the protocol and security boundaries. + +Version 0.3.0 is proposed because MCP Apps adds a user-facing feature. Development +and plugin metadata use that version. No tag, release, or plugin publication is +part of this change. Qualification still follows [RELEASING.md](RELEASING.md). + ## 0.2.0 (unreleased) ### Added diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c3cdddc..c89cf29 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,7 +18,7 @@ review; do not submit only a final source archive. ## Prerequisites -- Go 1.27.0. +- Go 1.27.2. - A Unix-like shell and make for the Makefile and shell scripts. - A C toolchain for race tests. - Network access to the Go module proxy for the first tool download. @@ -140,6 +140,26 @@ A spelling or link correction does not need a new behavior proposal. Run `make docs-check` for such edits. The ADR requirements still apply to public, wire, storage, security, and configuration changes. +## MCP Apps frontend + +The Go executable embeds the committed HTML bundle. Ordinary Go builds and +runtime use do not need Node.js. Frontend changes require Node.js 20.19.0 or +later and the browser dependencies described in the [MCP Apps guide](docs/mcp-apps.md). + +After installing the pinned npm dependencies, run: + +```sh +npm run app:build +npm run app:check +npm run app:test +npm run app:screenshots +``` + +Commit changed frontend sources with their rebuilt bundle. Inspect screenshots +before committing them, and use only synthetic fixtures. Tests must cover the +SDK lifecycle and meaningful interactions, including missing data and errors. +Keep tool payloads, read-only boundaries, and plain MCP compatibility stable. + ## Publication Do not publish a release or plugin from an unreviewed change. The release diff --git a/Makefile b/Makefile index 423edde..c8fa011 100644 --- a/Makefile +++ b/Makefile @@ -6,9 +6,9 @@ NPM ?= npm VHS ?= vhs BIN_DIR ?= bin -GO_VERSION := 1.27.0 +GO_VERSION := 1.27.2 GOIMPORTS_VERSION := v0.44.0 -GOLANGCI_LINT_VERSION := v2.13.2 +GOLANGCI_LINT_VERSION := v2.14.0 ACTIONLINT_VERSION := v1.7.12 GOVULNCHECK_VERSION := v1.7.0 GITLEAKS_VERSION := v8.30.1 diff --git a/NOTICE.md b/NOTICE.md index 13b0913..b6991bc 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -6,3 +6,11 @@ or sponsored by WeatherFlow or the Tempest weather platform. WeatherFlow and Tempest names and marks belong to their respective owners. Use of those names identifies compatible services and products. It does not imply an official relationship. + +## Embedded frontend dependencies + +The MCP Apps HTML bundle includes third-party JavaScript. Its +[generated source](internal/mcpapp/ui/app.html) retains the bundled packages' +license and notice text in an HTML comment. The +[asset builder](scripts/build-mcp-app.mjs) collects those texts from the pinned +dependencies. Rebuilding the app updates its code and notices together. diff --git a/README.md b/README.md index 2c2a102..2db3cb1 100644 --- a/README.md +++ b/README.md @@ -8,28 +8,58 @@ [![Go Reference][docs-badge]][go-docs] [![GitHub stars][stars-badge]][stars] -TempestKeep is a [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) -server and command-line tool for WeatherFlow Tempest. An MCP client can request -live conditions, forecasts, and historical queries. TempestKeep can collect -history into a local SQLite archive and resume interrupted collection. +Explore your WeatherFlow Tempest data inside your +[Model Context Protocol (MCP)](https://modelcontextprotocol.io/) client. +TempestKeep provides live weather, forecasts, and a local SQLite archive through +typed tools. +[MCP Apps](https://modelcontextprotocol.io/extensions/apps/overview) adds +interactive charts and tables directly to conversations in supporting hosts. -One Go executable serves MCP over stdio, the client's standard input and output. -The same executable provides a terminal dashboard, reports, and CSV or JSON Lines -exports. An existing archive works without a WeatherFlow token. +![Weather charts in the TempestKeep MCP App](docs/screenshots/mcp-app-weather.png) -[![MCP discovery, archive backfill, chained queries, and offline reuse][mcp-demo]][mcp-video] +*Synthetic weather in the local MCP Apps test host, captured with Playwright. +This preview does not certify a specific client.* + +[Connect your client](#connect-your-agent) · [Explore MCP Apps](#interactive-mcp-apps) +· [Try synthetic data](#try-it-without-a-station) · [CLI and terminal UI](#cli-and-terminal-ui) + +One Go executable serves MCP over stdio and includes the complete app UI. +You do not need Node.js, a web server, or the separate TUI to explore data in +an MCP Apps host. The same executable still provides terminal dashboards, +reports, and CSV or JSON Lines exports. An existing archive works without a token. + +## Interactive MCP Apps + +Ask for weather or an archive query, then explore the result in your conversation. +The host opens the view for the tool it calls. Use the same MCP connection and +credentials described below. + +| Explore | In the app | +|---|---| +| Weather over time | Switch chart metrics, explore the wind rose, and inspect exact readings in the table. | +| Archive and SQL results | Search rows, sort columns, and move between table pages. | +| Updated results | Refresh the same read-only tool with its original arguments. | +| Your working environment | Use responsive views that follow the host's light or dark theme. | -[Watch the MP4 clip][mcp-video] · [Run the demo locally](#try-it-without-a-station) -· [Connect your agent](#connect-your-agent) · [CLI and terminal UI](#cli-and-terminal-ui) +![Searchable archive table in the TempestKeep MCP App](docs/screenshots/mcp-app-table.png) -The clip uses synthetic weather and a scripted Go client. Discovery, tool calls, -archive writes, and the final session without an API token all run through the -real MCP server. No LLM or WeatherFlow account is needed to replay it. +*Synthetic table data in the local MCP Apps test host, captured with Playwright.* + +Search and pagination cover the returned rows. Views display up to 2,000 rows +and 64 columns, with a notice when a limit applies. If a server limit truncates +the result, narrow the tool request before drawing conclusions about the archive. +Missing readings remain distinct from zero. The app does not run archive writes. + +MCP Apps support depends on the host and its version. Clients without the +extension retain the existing text and structured tool results. See the +[MCP Apps guide](docs/mcp-apps.md) for usage, host compatibility, privacy, and +screenshot reproduction. ## What your agent can do With live access and a writable archive, TempestKeep exposes 29 typed tools, -2 resources, and 3 prompts. Each tool has an input schema and structured output. +2 archive documentation resources, and 3 prompts. Each tool has an input schema +and structured output. The 27 read-only tools also have MCP Apps UI resources. | Ask your agent | MCP workflow | |---|---| @@ -62,7 +92,7 @@ See the [MCP guide](docs/mcp.md) for configuration, capabilities, and limits. ### Build -You need Go 1.27.0 and a local filesystem for SQLite. Live data and collection +You need Go 1.27.2 and a local filesystem for SQLite. Live data and collection also need a WeatherFlow personal access token. The build commands below use `make` and a Unix-like shell. The normal build uses pure Go. Race tests need a C toolchain. @@ -125,12 +155,23 @@ Diagnostics go to stderr. SIGINT and SIGTERM cancel work and close the archive. The archive remains local. Tool results go to the connected MCP client, which can send them to its model provider. +In an MCP Apps host, ask for a forecast, daily summary, or SQL query to open its +interactive result. Reconnect after replacing an older binary so the client +refreshes its tool list. No additional TempestKeep app configuration is required. + The optional [Claude Code plugin](plugin/README.md) uses the same server. +A plugin connection alone does not establish MCP Apps support in that client. ## Try it without a station -Run the same MCP session shown above with a local synthetic API and a temporary -archive. No real token or model provider is used: +[![MCP discovery, archive backfill, chained queries, and offline reuse][mcp-demo]][mcp-video] + +[Watch the MP4 clip][mcp-video]. The clip uses a scripted Go client and synthetic +weather. Discovery, tool calls, archive writes, and offline reuse run through the +real MCP server. It demonstrates the underlying MCP tools, rather than the app UI. + +Run that MCP session with a local synthetic API and a temporary archive. +No real token or model provider is used: ```sh make mcp-demo @@ -198,9 +239,10 @@ cycles the month/year metric. The `g` or Home key returns to the latest period. The `q`, Esc, and Ctrl+C keys exit either dashboard. `tempestkeep version` reports the build's injected version, then Go's module -version when available. If neither exists, it falls back to `v0.2.0-dev`. +version when available. If neither exists, it falls back to `v0.3.0-dev`. `make build` injects a version from Git tags or that development fallback. -See [CHANGELOG.md](CHANGELOG.md) for the pending minor-version changes. +Version 0.3.0 is the proposed next minor release. See [CHANGELOG.md](CHANGELOG.md) +for its scope. This change does not publish a release. ## Archive behavior @@ -252,7 +294,7 @@ See [SECURITY.md](SECURITY.md) for private reporting and the ## Verification -Run the repository checks with Go 1.27.0: +Run the repository checks with Go 1.27.2: ```sh make fmtcheck # gofmt and goimports @@ -290,12 +332,15 @@ deletes that archive. It discards API output. Do not run it with a production to CI runs on pushes to `main`, pull requests, and manual dispatch. Ubuntu runs the full Go checks. macOS and Windows run native tests, documentation checks, -and pure-Go builds. A separate job validates the OpenSpec requirements. +and pure-Go builds. Separate jobs validate OpenSpec requirements and the MCP +Apps bundle and browser behavior. CI cancels obsolete runs. Demo recording and release qualification are manual. Release qualification -builds a snapshot and does not publish it. OpenSpec's Node.js dependency is -development tooling and is not required to build or run TempestKeep. +builds a snapshot and does not publish it. Node.js is development tooling for +OpenSpec and the MCP Apps frontend. It is not required to build or run TempestKeep. +For UI changes, run the [frontend checks](docs/mcp-apps.md#develop-and-test-the-app) +in addition to the Go checks. Use the [documentation index](docs/README.md) to find command guides, design records, security evidence, support policy, and release procedures. See @@ -337,7 +382,7 @@ Tempest names and marks belong to their respective owners. See [NOTICE.md](NOTIC TempestKeep uses the MIT License. See [LICENSE](LICENSE). -[version-badge]: https://img.shields.io/badge/development-v0.2.0--dev-blue +[version-badge]: https://img.shields.io/badge/development-v0.3.0--dev-blue [ci-b]: https://img.shields.io/github/actions/workflow/status/lennrt/tempestkeep/ci.yml?branch=main [ci]: https://github.com/lennrt/tempestkeep/actions/workflows/ci.yml [license-badge]: https://img.shields.io/github/license/lennrt/tempestkeep diff --git a/RELEASING.md b/RELEASING.md index 0b94f10..6f78a21 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -9,7 +9,7 @@ remains disabled until a separate reviewed change enables an approved release. - Obtain explicit release approval. - Select one reviewed commit with a clean working tree. - Require all configured GitHub checks to pass for that commit. -- Use Go 1.27.0. +- Use Go 1.27.2. - Confirm that no credential, station data, archive, export, personal path, or raw API response is present in tracked, untracked, ignored, or generated files. @@ -29,7 +29,7 @@ Choose a semantic version. Do not reuse or move a published tag. Use `vMAJOR.MINOR.PATCH` for release tags and the corresponding SemVer version for artifacts. Development snapshots retain the exact source commit as their -unique identifier; `v0.2.0-dev` alone does not identify a source revision. +unique identifier; `v0.3.0-dev` alone does not identify a source revision. Update [CHANGELOG.md](CHANGELOG.md) with a human-readable account of changes, compatibility effects, and upgrade instructions. Include every publicly known @@ -48,7 +48,7 @@ make integration e2e make release-check ``` -The Go version must be exactly 1.27.0. The first three commands must pass. The +The Go version must be exactly 1.27.2. The first three commands must pass. The last command creates local snapshot archives in `dist/` without publishing them. Inspect every archive. Confirm that it contains the `tempestkeep` binary, diff --git a/SUPPORT.md b/SUPPORT.md index b7b0599..07a82b2 100644 --- a/SUPPORT.md +++ b/SUPPORT.md @@ -12,7 +12,7 @@ Do not put sensitive station data in either channel. [docs/README.md](docs/README.md). 2. Read the [troubleshooting guide](docs/troubleshooting.md) for known recovery steps. 3. Run `tempestkeep help ` or inspect the MCP tool description. -4. Reproduce the problem with the default branch and Go 1.27.0 when practical. +4. Reproduce the problem with the default branch and Go 1.27.2 when practical. 5. Run the smallest relevant check from [CONTRIBUTING.md](CONTRIBUTING.md). ## Include diff --git a/cmd/tempestkeep/README.md b/cmd/tempestkeep/README.md index 62c89fe..d9a1531 100644 --- a/cmd/tempestkeep/README.md +++ b/cmd/tempestkeep/README.md @@ -6,7 +6,7 @@ one device. ## Build -Use Go 1.27.0 from the repository root: +Use Go 1.27.2 from the repository root: ```sh make tempestkeep diff --git a/docs/README.md b/docs/README.md index 9628c82..67f7a9c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -9,6 +9,8 @@ building, setup, collection, MCP operation, privacy, and verification. displays, exports, and configuration precedence. - [`tempestkeep mcp` guide](mcp.md): MCP inputs, capabilities, limits, and startup behavior. +- [MCP Apps guide](mcp-apps.md): interactive views, host compatibility, privacy, + frontend development, and synthetic screenshot reproduction. - [Query guide](querying.md): working tool and SQL examples, units, timezones, aggregation, and missing observations. - [Troubleshooting](troubleshooting.md): connection, configuration, collection, @@ -32,6 +34,12 @@ building, setup, collection, MCP operation, privacy, and verification. - [Reliability and specification ADR](adr/0005-reliability-and-specifications.md): checkpoint, API, query, backfill, and specification workflow decisions. +- [MCP Apps ADR](adr/0006-mcp-apps.md): embedded views, protocol compatibility, + browser boundaries, and the proposed 0.3.0 release. + +- [Go patch toolchain ADR](adr/0007-go-patch-toolchain.md): the Go 1.27.2 pin and + qualification of the updated toolchain. + ## Review correctness and security - [Correctness properties](testing/properties.md): guarantees converted into @@ -61,7 +69,9 @@ building, setup, collection, MCP operation, privacy, and verification. The four `.tape` files use the local mock API. They do not need a station or token. -- [MCP recording guide](demo.md): replay, smoke check, and record the lead demo. +- [MCP recording guide](demo.md): replay, smoke check, and record the tool demo. +- [MCP Apps screenshots](mcp-apps.md#reproduce-the-screenshots): capture the + embedded app with Playwright and synthetic data. - [CLI and MCP demo](demo.tape) - [Setup demo](setup.tape) - [MCP agent demo](agent.tape) diff --git a/docs/adr/0001-modern-go-engineering-baseline.md b/docs/adr/0001-modern-go-engineering-baseline.md index f08cfed..1e1e26e 100644 --- a/docs/adr/0001-modern-go-engineering-baseline.md +++ b/docs/adr/0001-modern-go-engineering-baseline.md @@ -5,6 +5,9 @@ - Owner: Repository maintainer - Scope: Public Go API, configuration, storage, wire formats, CI, and releases +The Go patch pin in this record is superseded by +[ADR 0007](0007-go-patch-toolchain.md). The remaining baseline decisions stay in effect. + ## Context The initial repository state contains a README and MIT license. This decision @@ -17,9 +20,9 @@ context. Some public inputs and returned collections are not bounded. ## Decision -Use Go 1.27.0, the stable release listed by `https://go.dev/dl/?mode=json` on -2026-08-29. Pin that exact patch in the module, CI, release jobs, and operator -documentation. +The initial baseline selected the stable Go release listed by +`https://go.dev/dl/?mode=json` on 2026-08-29. Pin the supported patch in the module, +CI, release jobs, and operator documentation. See ADR 0007 for the current pin. Establish the package surface as the compatibility baseline: @@ -66,8 +69,9 @@ SBOM generation. ## Consequences -The minimum Go version becomes 1.27.0. Contributors and CI may download that -toolchain through Go's verified toolchain mechanism. +The initial minimum Go version matched the stable release on the recorded date. +Contributors and CI can download the current pinned toolchain through Go's +verified toolchain mechanism. The stronger API contracts require call-site and test updates for this baseline. CI gains additional security jobs and therefore uses more runner time. No diff --git a/docs/adr/0003-openssf-security-baseline.md b/docs/adr/0003-openssf-security-baseline.md index eea3ae9..a12e53c 100644 --- a/docs/adr/0003-openssf-security-baseline.md +++ b/docs/adr/0003-openssf-security-baseline.md @@ -4,6 +4,8 @@ Accepted for development before the first stable release. +The linter patch pin is superseded by [ADR 0007](0007-go-patch-toolchain.md). + ## Context The OpenSSF Passing assessment needs evidence of implemented practices. Existing @@ -27,7 +29,7 @@ HTTP error for 3xx responses without contacting the redirect destination. Keep explicit test endpoints and borrowed HTTP clients available; callers must trust their transport and preserve the security policy for real credentials. -Build pinned golangci-lint v2.13.2 through `make lint` with the required Go +Build pinned golangci-lint through `make lint` with the required Go toolchain. Its updated Staticcheck supports Go 1.27's Linux standard library; the v2.12.2 analyzer panics on that library's new syntax. Keep Scorecard output in its workspace and retain it as a workflow artifact. An diff --git a/docs/adr/0006-mcp-apps.md b/docs/adr/0006-mcp-apps.md new file mode 100644 index 0000000..0d65bdf --- /dev/null +++ b/docs/adr/0006-mcp-apps.md @@ -0,0 +1,86 @@ +# ADR 0006: Embed read-only MCP Apps in the existing server + +## Status + +Proposed in the MCP Apps pull request. Version 0.3.0 is the proposed minor +release. This change does not publish a release or plugin. + +## Context + +TempestKeep returns structured weather and archive results over MCP. Large +tables and weather series need a visual view inside the user's MCP client. +Requiring the terminal dashboard interrupts that conversation and excludes +clients without access to the user's terminal. + +The [MCP Apps extension][apps] lets a server associate an HTML resource with +a tool. The client, also called the host, renders that resource in a sandbox. +The existing typed tool results remain the source of data. + +## Decision + +Associate each registered read-only tool with a resource at +`ui://tempestkeep/.html` through `_meta.ui.resourceUri` when the client advertises +MCP Apps MIME support. +Serve the resource with MIME type `text/html;profile=mcp-app`. +Register resources according to the same live-client and archive capabilities +as their tools. Keep write tools without an app association. + +Embed a self-contained HTML bundle in the Go executable. Use the official +`@modelcontextprotocol/ext-apps` SDK for initialization, tool notifications, +theme updates, and tool calls through the host. Pin development dependencies +and commit the generated bundle. Building or running Go does not require Node.js, +a local HTTP server, or a separate frontend process. + +Render supported weather series as charts and tabular results as tables with +search, sorting, and pagination. Preserve labels, units, dates, missing readings, +and server truncation notices. Render untrusted result values as text. The view +must distinguish loading, empty results, failed calls, and valid zero readings. + +Refresh repeats the associated read-only tool with its last supplied arguments. +The host mediates that call and can deny it. Do not expose controls for archive +backfill or sync. Keep query and result limits in the existing Go handlers. +Table search, sorting, and pagination operate on the returned rows only. + +Request no external connection or resource origins in the app's content +security policy. Request no device permissions. Keep API credentials and archive +access in the Go server. The app receives tool inputs and results from the host, +so the host's handling of those data remains a privacy boundary. + +Keep the active OpenSpec proposal available during review. The baseline MCP +specification also records these requirements so readers can find the complete +service contract without opening a proposal. + +## Compatibility + +This is an additive MCP change: supporting clients see app metadata in tool +discovery, and resource discovery gains HTML resources. Existing tool names, input schemas, +structured +result shapes, annotations, and capability rules remain unchanged. Clients +without MCP Apps support can continue to use ordinary tool results. + +There is no public Go signature, archive schema, configuration, or TUI change. +Existing archives require no migration. Node.js dependencies apply only to +development checks and rebuilding the embedded frontend. The compiled Go +application remains compatible with `CGO_ENABLED=0`. + +The proposed 0.3.0 version identifies a new user-facing feature. Keep the +development version, plugin manifest, and release notes consistent. Publication +still requires the separate procedure in [RELEASING.md](../../RELEASING.md). + +## Validation + +Use real MCP transports to test resource discovery, MIME type, tool metadata, +read-only annotations, unsupported resources, and every capability combination. +Assert that original structured results and write-tool boundaries remain intact. + +Use Playwright with a local MCP Apps test host and synthetic fixtures. Exercise +the SDK lifecycle, refresh, theme updates, sorting, search, pagination, empty +states, failures, missing values, and hostile text. Capture weather and table +screenshots from the same embedded bundle. These previews do not certify a +specific third-party host. + +Run documentation, strict OpenSpec, frontend build, frontend browser, and +applicable Go checks. Record exact results and unavailable prerequisites in +the pull request. Do not present screenshots as proof of server correctness. + +[apps]: https://modelcontextprotocol.io/extensions/apps/overview diff --git a/docs/adr/0007-go-patch-toolchain.md b/docs/adr/0007-go-patch-toolchain.md new file mode 100644 index 0000000..aea6a6c --- /dev/null +++ b/docs/adr/0007-go-patch-toolchain.md @@ -0,0 +1,43 @@ +# ADR 0007: Pin Go 1.27.2 for builds and qualification + +## Status + +Proposed in pull request #7 on 2026-10-12. This supersedes only the Go patch +version in [ADR 0001](0001-modern-go-engineering-baseline.md) and the linter pin +in [ADR 0003](0003-openssf-security-baseline.md). + +## Context + +The MCP Apps verification run reported standard-library vulnerabilities in the +previously pinned Go toolchain. The repository needs a consistent patch update +across local builds, required checks, CI, release qualification, and instructions. + +## Decision + +Pin Go 1.27.2 in the module, Makefile, CI workflows, and active documentation. +Keep the exact-version guard so local verification uses the same patch as CI. +Require the normal repository checks and vulnerability scan with that toolchain. +Record their actual results in the pull request and active change evidence. + +Pin golangci-lint v2.14.0. The previous v2.13.2 fails to read Go 1.27.2 compiler +export data (version 5 exceeds its supported version 4). The updated linter +includes a newer Go tools dependency and passes the existing configuration +without disabling any checks. + +Keep dated test records accurate. A past run with the previous toolchain remains +historical evidence and does not establish results for Go 1.27.2. Keep the +existing rule that missing prerequisites and failed checks do not count as passes. + +## Compatibility + +The minimum Go patch version increases to 1.27.2. Contributors and CI must use +that version for repository verification. The update adds no application API, +MCP schema, archive, configuration, or command change. The proposed application +version stays 0.3.0. This change does not tag or publish a release. + +## Validation + +Run `make verify` with Go 1.27.2, including `make vuln`. Run the frontend and +OpenSpec checks as required by the active MCP Apps change. Inspect every active +toolchain pin and record remaining historical references as historical evidence. +Do not infer a passing vulnerability scan from the version change alone. diff --git a/docs/architecture.md b/docs/architecture.md index 9b3a396..dd7d0b4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -TempestKeep builds one Go 1.27.0 command over one shared core: +TempestKeep builds one Go 1.27.2 command over one shared core: - `tempestkeep` owns setup, collection, export, reports, and terminal views. - `tempestkeep mcp` exposes live and archived data over MCP stdio. @@ -15,6 +15,7 @@ flowchart LR CORE[pkg/tempest] DB[(SQLite archive)] CLIENT[MCP client] + VIEW[Sandboxed MCP App] APP --> CLI APP --> MCP @@ -23,6 +24,8 @@ flowchart LR CORE -->|authenticated HTTPS reads| WF CORE -->|read-only queries or constrained writes| DB CLIENT <-->|JSON-RPC over stdio| MCP + CLIENT <-->|MCP Apps bridge| VIEW + MCP -->|embedded HTML resource| CLIENT ``` ## API and collection path @@ -125,6 +128,29 @@ Stdout carries MCP JSON-RPC only. Stderr carries bounded, redacted diagnostics. The server does not log local archive paths, tokens, response bodies, station coordinates, serial numbers, or raw identifiers. +## MCP Apps + +The server embeds one self-contained frontend bundle and serves a resource for +each available read-only tool. App-capable clients receive the association through +`_meta.ui.resourceUri`. Resource URIs use `ui://tempestkeep/.html` and +MIME type `text/html;profile=mcp-app`. Ordinary clients retain their original tool +metadata and results. Both kinds of client can inspect registered UI resources. + +The host renders the app in its sandbox. The official MCP Apps SDK receives +tool inputs, tool results, and host context. Refresh repeats the associated +read-only tool through the host. Existing Go handlers retain ownership of API +calls, database reads, input validation, deadlines, and result limits. + +The frontend shows supported charts, interactive tables, and structured details. +Its search, sort, and pagination state applies to returned rows. It cannot +collect history or bypass server truncation. API credentials remain in Go. +The resource requests no external network or asset origins and no device permissions. + +Node.js is required only to rebuild and test the frontend during development. +The committed HTML bundle lets Go builds remain independent of npm and keeps +runtime deployment to one executable. See the [MCP Apps guide](mcp-apps.md) and +[ADR 0006](adr/0006-mcp-apps.md). + ## Verification `make verify` runs formatting, import, module, vet, unit, integration, race, @@ -132,3 +158,6 @@ fuzz, lint, generated API, vulnerability, license, SBOM, secret, pure-Go, and Linux ARM64 checks. It also checks GitHub Actions with pinned actionlint. See [testing/properties.md](testing/properties.md) and [threat-model.md](threat-model.md). + +Frontend changes also require the generated-bundle and Playwright browser checks +in the [MCP Apps development guide](mcp-apps.md#develop-and-test-the-app). diff --git a/docs/demo.md b/docs/demo.md index d764df5..8d8c517 100644 --- a/docs/demo.md +++ b/docs/demo.md @@ -12,7 +12,7 @@ Questions and narration are scripted. Counts, tool results, and summaries come from actual protocol exchanges against synthetic weather data. There is no LLM in the recording and no claim about a particular model's tool selection. -1. Discover the server, 29 tools, 2 resources, and 3 prompts. +1. Discover the server, 29 tools, 29 resources (27 app views and 2 archive guides), and 3 prompts. 2. Build 45 days of synthetic history through repeated bounded backfill calls. 3. Select the strongest gust in the last 30 days, then inspect that day's hourly observations. The comparison uses hourly mean wind speed. Each hourly gust field @@ -27,7 +27,7 @@ samples with a wind speed. ## Run and verify -With Go 1.27.0 installed: +With Go 1.27.2 installed: ```sh make mcp-demo # paced terminal demonstration diff --git a/docs/mcp-apps.md b/docs/mcp-apps.md new file mode 100644 index 0000000..cee6833 --- /dev/null +++ b/docs/mcp-apps.md @@ -0,0 +1,167 @@ +# Interactive MCP Apps + +TempestKeep displays weather and archive results inside MCP clients that support +the [MCP Apps extension][apps]. The client is the host: it renders the app and +routes its read-only requests to the existing TempestKeep server. + +The app ships inside the Go executable. It needs no web server, Node.js runtime, +or separate TUI. Clients without MCP Apps support still receive normal text and +structured tool results. + +## Connect and explore + +Use the [MCP connection instructions](../README.md#connect-your-agent) to configure +`tempestkeep mcp`. Configure a token for live weather or an existing archive for +local queries. The same capability rules apply to the app and ordinary tools. + +1. Reconnect the client after installing the updated binary. +2. Ask for a forecast, daily summary, or another available read-only result. +3. Open the app view that the host associates with that tool call. + +The host decides where the view appears. Some clients require you to expand +the tool result. Host support and permission controls vary by version. Use the +[official MCP Apps documentation][apps] to find current host support. +This repository does not certify a particular host or version. + +| Request | What to explore | +|---|---| +| "Show the forecast." | Supported weather series and their returned readings. | +| "Show daily weather for the past month." | Trends and a table of daily summaries. | +| "Show the windiest days in my archive." | Ranked rows from a summary or read-only SQL result. | +| "Show the archive status." | Coverage and the available structured details. | + +All 27 read-only tools have views when live and archive sources are available. +Only tools supported by the current configuration appear. `backfill_archive` +and `sync_archive` retain their ordinary MCP results and have no app controls. + +## Read charts and tables + +Charts show supported weather series with a metric selector. Hover over bars +or line series with up to 60 readings to see values. For larger line series, +use the table for exact readings. Wind results include a 16-sector rose. +Dataset tabs separate collections +such as hourly and daily forecasts. Tables provide text search, numeric-aware +column sorting, and eight-row pages. These controls operate on the received +result. They do not run a new archive query or retrieve rows beyond a server limit. + +The view displays at most 2,000 rows and 64 columns per table. It reports when +these display limits omit data. The original structured tool result remains +available to the host. Long cell text is also bounded in the display. + +If a result is truncated, narrow its dates, reduce its selected columns, or use +an aggregate query. The truncation notice remains visible during table +interaction. A table page is not evidence that the archive is complete. + +Missing readings remain distinct from measured zero. Labels and field units +come from the tool result. Raw SQL retains SI units unless the query explicitly +converts them. SQL column names and values remain in their original order, even +when names repeat. The app does not infer units from arbitrary SQL column names. +See the [query guide](querying.md) for date boundaries, aggregation, and incomplete +sensor coverage. + +Refresh repeats the current read-only tool with the same arguments through the +host. Live tools retain the configured API cache behavior. Archive views read +the archive's current contents. Refresh does not sync or backfill history. +For a different range or query, ask the agent to call the tool with new arguments. + +The view follows the host's theme and fits narrow containers. Loading, empty +results, and errors have explicit states. If the host denies refresh, the app +reports the unavailable action. It does not open another connection to the API. + +## Privacy and resource boundaries + +The host supplies tool inputs and results to the app. These data can include +station details, weather history, and query text. Configure trusted hosts and +review their retention and model-provider policies. + +The frontend receives no WeatherFlow token and does not open SQLite files. +The existing Go tool handlers enforce read-only queries, limits, and deadlines. +The app renders external labels and cell values as text. + +Scripts and styles are bundled into the HTML resource. Its content security +policy requests no external connection, resource, or frame origins. It requests +no camera, microphone, location, or other device permissions. The host supplies +the sandbox and controls tool-call permissions. See the +[threat model](threat-model.md) for the full boundary and residual risks. + +## Discovery contract + +An app-capable client advertises the `io.modelcontextprotocol/ui` extension +with `text/html;profile=mcp-app` in its supported MIME types. TempestKeep then +includes `_meta.ui.resourceUri` on each available read-only tool. + +The URI is `ui://tempestkeep/.html`. `resources/read` returns HTML with +MIME type `text/html;profile=mcp-app`. Resources follow the data-source capability +rules and remain available for inspection by ordinary MCP clients. With every +source available, there are 27 UI resources and two archive documentation resources. + +Clients that do not advertise the extension see their ordinary tool metadata. +The tool's input schema, annotations, text content, and structured result stay +the same in either mode. See the [service specification](../openspec/specs/mcp-service/spec.md) +and [ADR 0006](adr/0006-mcp-apps.md) for the proposed contract. + +## Troubleshooting + +| Symptom | Action | +|---|---| +| Only text appears | Make sure that the client version supports MCP Apps, then reconnect and expand the tool result. | +| An expected view is absent | Inspect tool discovery. Live-only tools need a token, and archive tools need an archive. | +| Refresh is unavailable | Use the host's tool-call controls or ask the agent to repeat the same read-only tool. | +| Archive data does not become newer | Run the normal sync or collection workflow, then refresh the view. | +| A table search finds no rows | Clear the search and inspect the range, returned row count, and truncation notice. | +| The view is empty or reports an error | Inspect the tool result and the server's redacted stderr diagnostics. | + +Do not add an HTTP listener or expose your token to the browser to fix a host +compatibility problem. Ordinary MCP results remain available. See the +[MCP troubleshooting guide](troubleshooting.md) for connection and archive issues. + +## Develop and test the app + +Use Node.js 20.19.0 or later for frontend and specification development. The +lockfile pins the SDK, bundler, browser tooling, and OpenSpec dependencies. +From the repository root, install dependencies and the test browser: + +```sh +npm ci --ignore-scripts --no-audit --no-fund +npx playwright install chromium +``` + +On a fresh Linux machine, Playwright can also need system browser dependencies. +Use `npx playwright install --with-deps chromium`, as the CI workflow does. +Building the ordinary Go executable uses the committed HTML and does not run npm. + +```sh +npm run app:build +npm run app:check +npm run app:test +npm run spec:check +make docs-check +``` + +The build creates the self-contained HTML embedded by Go. Commit source changes +with the rebuilt bundle. The generated-asset check detects stale output. +The bundle also retains third-party license and notice text. See +[NOTICE.md](../NOTICE.md) for the source and generation process. +Browser tests use a local test host with the official MCP Apps bridge and +synthetic fixtures. They do not need a WeatherFlow token or a model provider. + +## Reproduce the screenshots + +After installing the development dependencies and Chromium, run: + +```sh +npm run app:build +npm run app:screenshots +``` + +Playwright captures the embedded app in the local synthetic test host. The +generated files are [the weather preview](screenshots/mcp-app-weather.png) and +[the table preview](screenshots/mcp-app-table.png). Inspect both images before +committing them with a UI change. + +These screenshots show fixture data and the app's layout. They are not captures +of a production station or evidence of compatibility with a named third-party +host. Keep credentials, personal paths, station identifiers, and real weather +archives out of fixtures and screenshots. + +[apps]: https://modelcontextprotocol.io/extensions/apps/overview diff --git a/docs/mcp.md b/docs/mcp.md index ed6eede..ce0250e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6,7 +6,7 @@ input and output. This command does not start an HTTP server or open a port. ## Build and connect -Use Go 1.27.0 from the repository root: +Use Go 1.27.2 from the repository root: ```sh make tempestkeep @@ -54,8 +54,9 @@ The client discovers the capabilities that match the current configuration: | Token and archive | All live and archive reads | | Token and writable archive | All reads, plus `backfill_archive` and `sync_archive` | -An archive enables two resources and three workflow prompts. The resources are -`tempest://archive/schema` and `tempest://archive/data-dictionary`. The prompts +An archive enables two documentation resources and three workflow prompts. The +resources are `tempest://archive/schema` and `tempest://archive/data-dictionary`. +The prompts are `weather_report`, `climate_review`, and `build_archive`. A prompt does not enable tools that the configuration excludes. @@ -73,6 +74,28 @@ belongs to that station. Missing or mismatched identity leaves those fields absent. Do not assume that live weather and a configured archive describe the same station. See the [query guide](querying.md) before combining their results. +## MCP Apps + +Supporting hosts can display interactive weather charts and tables for all +available read-only tools. Use the same server configuration. Reconnect after +updating the binary, then ask for a forecast, daily summary, or archive query. +The host associates its result with the embedded app. + +The app supports table search, sorting, pagination, and refresh through the +same read-only tool. Table controls operate on returned rows. Refresh does not +backfill or sync history. `backfill_archive` and `sync_archive` have no app view. + +App-capable hosts receive `_meta.ui.resourceUri` in tool discovery. Each URI +names a `text/html;profile=mcp-app` resource at +`ui://tempestkeep/.html`. Available tools determine the registered +resources. With all capabilities enabled, 27 UI resources supplement the two +archive documentation resources. + +Clients without MCP Apps support retain the existing tool results and ordinary +tool metadata. Node.js and an HTTP listener are not needed to run the app. +See the [MCP Apps guide](mcp-apps.md) for host support, data limits, privacy, +and reproducible screenshots. + ## Start and stop For an existing archive, use this command without `TEMPEST_TOKEN` in the process diff --git a/docs/openspec.md b/docs/openspec.md index b6f59e4..62bce11 100644 --- a/docs/openspec.md +++ b/docs/openspec.md @@ -11,8 +11,8 @@ An OpenSpec proposal supplements the architecture decisions in [docs/adr](adr). ## Install the development tool Use Node.js 20.19.0 or later with npm. The lockfile pins OpenSpec and its -dependencies. Node.js is needed only for specification work. Building and -running the Go application does not require it. +dependencies. Node.js supports specification checks and MCP Apps frontend +development. Building and running the Go application does not require it. From the repository root, run these commands: diff --git a/docs/openssf.md b/docs/openssf.md index d4dee5f..a6b8f9b 100644 --- a/docs/openssf.md +++ b/docs/openssf.md @@ -42,7 +42,7 @@ another project's copied answers. Recheck time-dependent claims on each update. ## Reproduce the engineering evidence -Use Go 1.27.0 and a C toolchain for race checks. No live WeatherFlow token is +Use Go 1.27.2 and a C toolchain for race checks. No live WeatherFlow token is needed: ```sh @@ -56,10 +56,11 @@ vulnerabilities, licenses, SBOM generation, secrets, and pure-Go builds for the host and Linux ARM64. Missing tools and failed checks must return failure. `make cover` measures statements, not branches; inspect untested behavior too. -Local result on 2026-09-05: `make verify` passed with Go 1.27.0, including all -three fuzz targets, race checks, zero lint issues, and no reported vulnerabilities -or leaked credentials. A simulated imports-tool failure also correctly caused -`make fmtcheck` to fail. GitHub workflow results must be checked after pushing. +Local result on 2026-09-05: `make verify` passed with the then-pinned Go toolchain. +That run included all three fuzz targets, race checks, zero lint issues, and no +reported vulnerabilities or leaked credentials. A simulated imports-tool failure +also correctly caused `make fmtcheck` to fail. GitHub workflow results must be +checked after pushing. The 2026-09-05 coverage run measured 70.0% of statements overall. Store, model, collector, API, and MCP packages have substantial coverage, while some command diff --git a/docs/screenshots/mcp-app-table.png b/docs/screenshots/mcp-app-table.png new file mode 100644 index 0000000..c69bdf3 Binary files /dev/null and b/docs/screenshots/mcp-app-table.png differ diff --git a/docs/screenshots/mcp-app-weather.png b/docs/screenshots/mcp-app-weather.png new file mode 100644 index 0000000..300f7ac Binary files /dev/null and b/docs/screenshots/mcp-app-weather.png differ diff --git a/docs/testing/properties.md b/docs/testing/properties.md index 95682bc..a856471 100644 --- a/docs/testing/properties.md +++ b/docs/testing/properties.md @@ -3,7 +3,7 @@ This catalog converts repository guarantees into test targets. A passing test is evidence for the tested case. It is not proof of the general property. -All commands require Go 1.27.0. Tests have finite timeouts. Focused fuzz tests +All commands require Go 1.27.2. Tests have finite timeouts. Focused fuzz tests store any failing input in the Go fuzz corpus so the failure can be replayed. | ID | Property | Faults and boundaries | Current verification | diff --git a/docs/threat-model.md b/docs/threat-model.md index bc46a8a..028fe0b 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -3,9 +3,9 @@ ## Scope This model covers `tempestkeep`, its MCP mode, the shared Go packages, the local -SQLite archive, configuration files, and repository automation. It does not -cover the WeatherFlow service, the MCP client, the operating system, or GitHub -as trusted implementations. +SQLite archive, embedded MCP Apps frontend, configuration files, and repository +automation. It does not cover the WeatherFlow service, the MCP client, the +operating system, or GitHub as trusted implementations. ## Protected assets @@ -19,7 +19,7 @@ as trusted implementations. ## Trust roots - The user and the local operating-system account. -- The Go 1.27.0 toolchain and Go checksum database. +- The Go 1.27.2 toolchain and Go checksum database. - The configured WeatherFlow HTTPS endpoint. - Full commit SHAs in GitHub Actions. - The repository's reviewed source and generated API snapshot. @@ -36,6 +36,7 @@ as trusted implementations. | Read-only SQL | Arbitrary query text and large results | One statement; SELECT/CTE filter; SQLite `query_only`; time, byte, row, and column limits | Cancel or return `ErrResultTooLarge` or `ErrInvalidArgument` | | Backup directory | Collision, unrelated files, permissive mode, and large directory | Owner-only mode; exact filename format; entry limit; atomic no-overwrite link | Preserve existing backups and return failure | | MCP stdio | Tool arguments and untrusted archive/API values | Generated schemas; input bounds; stdout reserved for JSON-RPC; redacted stderr | Return a tool error without raw diagnostic data | +| MCP Apps sandbox | Tool arguments, result cells, API labels, and host messages | Official SDK bridge; text rendering; same-tool read-only refresh; self-contained assets; no external CSP origins or device permissions | Show a bounded error or empty state without direct API or archive access | | CI and tools | Dependency updates, mutable actions, and malicious history | Full action SHAs; minimum permissions; exact Go and tool versions; checksums; secret and dependency scans | Required job fails | ## Diagnostic sinks @@ -61,6 +62,10 @@ outputs, not diagnostics. Treat their output as sensitive. and restore procedures. - MCP clients can request and retain weather data. Configure only trusted clients and review their logging policy. +- The MCP Apps host controls the iframe sandbox, tool permissions, and retained + tool inputs and results. App CSP metadata cannot make an untrusted host safe. +- Embedded JavaScript is a distribution dependency. Review its pinned source, + generated asset, included license notices, and browser test results together. - Private-repository CodeQL and dependency review can require GitHub Advanced Security. A missing entitlement is an external blocker, not a passing skip. - No penetration test, formal verification, production load test, or Antithesis @@ -72,6 +77,8 @@ outputs, not diagnostics. Treat their output as sensitive. make test race fuzz lint generated make vuln licenses sbom secrets make build-pure build-arm64 +npm run app:check +npm run app:test ``` Before distribution, also inspect tracked, untracked, and ignored files; scan diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index ad5558c..ede64c4 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -23,6 +23,21 @@ When you run `tempestkeep mcp` in a terminal, it waits for protocol input. It does not display a dashboard. Use `tempestkeep now` for the dashboard. Do not redirect stderr into stdout in an MCP launch command. +## MCP tools work but no app appears + +Make sure that your host version supports the MCP Apps extension. Reconnect after +updating TempestKeep so the host refreshes tool discovery. Some hosts display +an app only after you expand its tool result. Ordinary tool output remains +available when the host does not render apps. + +UI resources follow tool availability. A missing token removes live-only tools, +and a missing archive removes archive queries. The archive write tools do not +have app views. The optional plugin does not add app rendering to a host. + +If refresh fails, inspect the host's tool-call permissions or ask the agent to +repeat the query. Refresh reads current data and does not collect new history. +See the [MCP Apps guide](mcp-apps.md#troubleshooting) for view-specific problems. + ## Configuration changes do not take effect Restart the process after changing its environment or `.env`. Commands read diff --git a/go.mod b/go.mod index 85465d0..4c4c074 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/lennrt/tempestkeep -go 1.27.0 +go 1.27.2 // Direct dependencies of note: // - github.com/modelcontextprotocol/go-sdk (official MCP SDK) diff --git a/internal/mcpapp/apps.go b/internal/mcpapp/apps.go new file mode 100644 index 0000000..c8610f8 --- /dev/null +++ b/internal/mcpapp/apps.go @@ -0,0 +1,109 @@ +package mcpapp + +import ( + "context" + _ "embed" + "maps" + "slices" + "strings" + + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +const ( + appMIMEType = "text/html;profile=mcp-app" + appExtension = "io.modelcontextprotocol/ui" +) + +// appHTML is built from the ui sources and committed so Go builds need no Node runtime. +// The template contains no weather data, credentials, or external dependencies. +// +//go:embed ui/app.html +var appHTML string + +// addAppTool keeps the normal typed handler and schemas, and adds a separate +// inspectable view resource. Callers use this only for read-only data tools. +// Registering the view alongside the tool preserves data-source capability gates. +func addAppTool[In, Out any](srv *mcp.Server, tool *mcp.Tool, handler mcp.ToolHandlerFor[In, Out]) { + uri := "ui://tempestkeep/" + tool.Name + ".html" + view := *tool + view.Meta = maps.Clone(tool.Meta) + if view.Meta == nil { + view.Meta = mcp.Meta{} + } + view.Meta["ui"] = map[string]any{"resourceUri": uri} + mcp.AddTool(srv, &view, handler) + + // Names come only from static tool registrations, never from a URI or data. + html := strings.ReplaceAll(appHTML, "__TEMPESTKEEP_TOOL__", tool.Name) + srv.AddResource(&mcp.Resource{ + URI: uri, Name: tool.Name + "_app", Title: tool.Title, + Description: "Interactive view of " + tool.Name + " results.", + MIMEType: appMIMEType, Size: int64(len(html)), Meta: appResourceMeta(), + }, func(_ context.Context, _ *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) { + return &mcp.ReadResourceResult{Contents: []*mcp.ResourceContents{{ + URI: uri, MIMEType: appMIMEType, Text: html, Meta: appResourceMeta(), + }}}, nil + }) +} + +// appResourceMeta lets hosts audit the static security policy before loading +// the view. Tool results arrive through the host bridge; the view needs no +// outbound requests, remote assets, nested frames, or browser permissions. +func appResourceMeta() mcp.Meta { + return mcp.Meta{"ui": map[string]any{ + "csp": map[string]any{ + "connectDomains": []string{}, "resourceDomains": []string{}, + "frameDomains": []string{}, "baseUriDomains": []string{}, + }, + "permissions": map[string]any{}, "prefersBorder": true, + }} +} + +// appToolsMiddleware negotiates presentation per request without mutating the +// shared tool definitions. Plain MCP clients retain the same tools, schemas, +// annotations, structured results, and text content without UI metadata. +// Resources stay discoverable so clients can inspect their static HTML/CSP. +func appToolsMiddleware(next mcp.MethodHandler) mcp.MethodHandler { + return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) { + result, err := next(ctx, method, req) + if err != nil || method != "tools/list" { + return result, err + } + request, ok := req.(*mcp.ListToolsRequest) + if !ok || supportsApps(request.ClientCapabilities()) { + return result, nil + } + listed, ok := result.(*mcp.ListToolsResult) + if !ok { + return result, nil + } + plain := *listed + plain.Tools = make([]*mcp.Tool, len(listed.Tools)) + for i, tool := range listed.Tools { + copy := *tool + copy.Meta = maps.Clone(tool.Meta) + delete(copy.Meta, "ui") + plain.Tools[i] = © + } + return &plain, nil + } +} + +func supportsApps(capabilities *mcp.ClientCapabilities) bool { + if capabilities == nil { + return false + } + settings, ok := capabilities.Extensions[appExtension].(map[string]any) + if !ok { + return false + } + switch mimeTypes := settings["mimeTypes"].(type) { + case []string: + return slices.Contains(mimeTypes, appMIMEType) + case []any: + return slices.Contains(mimeTypes, any(appMIMEType)) + default: + return false + } +} diff --git a/internal/mcpapp/apps_test.go b/internal/mcpapp/apps_test.go new file mode 100644 index 0000000..8934022 --- /dev/null +++ b/internal/mcpapp/apps_test.go @@ -0,0 +1,283 @@ +package mcpapp + +import ( + "context" + "net/http" + "net/http/httptest" + "path/filepath" + "reflect" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/lennrt/tempestkeep/pkg/tempest/api" + "github.com/lennrt/tempestkeep/pkg/tempest/store" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func appsClientCapabilities() *mcp.ClientCapabilities { + return &mcp.ClientCapabilities{Extensions: map[string]any{ + appExtension: map[string]any{"mimeTypes": []string{appMIMEType}}, + }} +} + +func connectAppsClient(t *testing.T, ctx context.Context, srv *mcp.Server, capabilities *mcp.ClientCapabilities) *mcp.ClientSession { + t.Helper() + clientTransport, serverTransport := mcp.NewInMemoryTransports() + serverSession, err := srv.Connect(ctx, serverTransport, nil) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, serverSession) + client := mcp.NewClient(&mcp.Implementation{Name: "apps-test", Version: "0"}, &mcp.ClientOptions{Capabilities: capabilities}) + session, err := client.Connect(ctx, clientTransport, nil) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, session) + return session +} + +// Exercise every source configuration through the wire, including capabilities +// negotiated at initialization and copied into the current protocol's requests. +func TestAppsRegistrationAndResources(t *testing.T) { + t.Parallel() + var requests atomic.Int32 + apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + requests.Add(1) + w.WriteHeader(http.StatusServiceUnavailable) + })) + t.Cleanup(apiServer.Close) + client, err := api.New("synthetic-test-token", api.WithBaseURL(apiServer.URL)) + if err != nil { + t.Fatal(err) + } + + for _, source := range []struct { + name string + live, archive, writable bool + readTools int + }{ + {name: "live", live: true, readTools: 4}, + {name: "archive", archive: true, readTools: 24}, + {name: "live and read-only archive", live: true, archive: true, readTools: 27}, + {name: "live and writable archive", live: true, archive: true, writable: true, readTools: 27}, + } { + t.Run(source.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) + defer cancel() + srv := mcp.NewServer(&mcp.Implementation{Name: "tempestkeep-test", Version: "0"}, nil) + var live *liveSource + if source.live { + live = &liveSource{client: client} + } + var st *store.Store + var writer *store.Writer + if source.archive { + path := filepath.Join(t.TempDir(), "archive.sqlite") + writer, err = store.OpenWriter(ctx, path) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, writer) + st, err = store.Open(ctx, path) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, st) + } + registerTools(srv, live, st) + if source.writable { + registerArchiveTools(srv, live, writer) + } + cs := connectAppsClient(t, ctx, srv, appsClientCapabilities()) + listed, err := cs.ListTools(ctx, nil) + if err != nil { + t.Fatal(err) + } + resources, err := cs.ListResources(ctx, nil) + if err != nil { + t.Fatal(err) + } + views := make(map[string]*mcp.Resource) + for _, resource := range resources.Resources { + if strings.HasPrefix(resource.URI, "ui://") { + views[resource.URI] = resource + } + } + if len(views) != source.readTools { + t.Fatalf("UI resources = %d, want %d", len(views), source.readTools) + } + readTools, writeTools := 0, 0 + for _, tool := range listed.Tools { + ui, hasUI := tool.Meta["ui"].(map[string]any) + if tool.Name == "sync_archive" || tool.Name == "backfill_archive" { + writeTools++ + if hasUI || tool.Annotations.ReadOnlyHint { + t.Errorf("write tool %s gained a UI or read-only annotation", tool.Name) + } + continue + } + readTools++ + uri := "ui://tempestkeep/" + tool.Name + ".html" + if !hasUI || ui["resourceUri"] != uri { + t.Errorf("tool %s UI = %#v, want %s", tool.Name, tool.Meta, uri) + } + if tool.Annotations == nil || !tool.Annotations.ReadOnlyHint || tool.InputSchema == nil || tool.OutputSchema == nil { + t.Errorf("tool %s lost annotations or typed schemas", tool.Name) + } + resource := views[uri] + if resource == nil { + t.Fatalf("tool %s references an unlisted resource", tool.Name) + } + if resource.MIMEType != appMIMEType { + t.Errorf("resource %s MIME = %q", uri, resource.MIMEType) + } + checkAppResourceMeta(t, resource.Meta) + read, err := cs.ReadResource(ctx, &mcp.ReadResourceParams{URI: uri}) + if err != nil || len(read.Contents) != 1 { + t.Fatalf("read %s = %#v, %v", uri, read, err) + } + content := read.Contents[0] + if content.URI != uri || content.MIMEType != appMIMEType || int64(len(content.Text)) != resource.Size { + t.Errorf("resource %s contents disagree with its listing", uri) + } + if !strings.Contains(strings.ToLower(content.Text), "") || !strings.Contains(content.Text, `data-tool="`+tool.Name+`"`) || strings.Contains(content.Text, "__TEMPESTKEEP_TOOL__") { + t.Errorf("resource %s is not a specialized HTML document", uri) + } + checkAppResourceMeta(t, content.Meta) + } + if readTools != source.readTools || (writeTools == 2) != source.writable { + t.Errorf("got %d read and %d write tools", readTools, writeTools) + } + for _, uri := range []string{"ui://tempestkeep/missing.html", "ui://tempestkeep/../app.html", "ui://tempestkeep/sync_archive.html"} { + if _, err := cs.ReadResource(ctx, &mcp.ReadResourceParams{URI: uri}); err == nil { + t.Errorf("read accepted unregistered resource %s", uri) + } + } + if !source.live { + if _, err := cs.ReadResource(ctx, &mcp.ReadResourceParams{URI: "ui://tempestkeep/forecast.html"}); err == nil { + t.Error("archive-only server exposed a live view") + } + } + if !source.archive { + if _, err := cs.ReadResource(ctx, &mcp.ReadResourceParams{URI: "ui://tempestkeep/archive_status.html"}); err == nil { + t.Error("live-only server exposed an archive view") + } + } + }) + } + if requests.Load() != 0 { + t.Error("UI registration or resource reads contacted the weather API") + } +} + +func checkAppResourceMeta(t *testing.T, meta mcp.Meta) { + t.Helper() + // Pin the security boundary independently of the metadata builder. + want := mcp.Meta{"ui": map[string]any{ + "csp": map[string]any{ + "connectDomains": []any{}, "resourceDomains": []any{}, + "frameDomains": []any{}, "baseUriDomains": []any{}, + }, + "permissions": map[string]any{}, "prefersBorder": true, + }} + if !reflect.DeepEqual(meta, want) { + t.Errorf("resource security metadata = %#v, want %#v", meta, want) + } +} + +func TestAppsCapabilityFallbackKeepsToolResults(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) + defer cancel() + st, err := store.Open(ctx, makeTestArchive(t)) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, st) + srv := mcp.NewServer(&mcp.Implementation{Name: "tempestkeep-test", Version: "0"}, nil) + registerTools(srv, nil, st) + appClient := connectAppsClient(t, ctx, srv, appsClientCapabilities()) + appTools, err := appClient.ListTools(ctx, nil) + if err != nil { + t.Fatal(err) + } + args := &mcp.CallToolParams{Name: "query_sql", Arguments: map[string]any{ + "sql": "SELECT epoch, air_temp_c, wind_avg FROM obs_st ORDER BY epoch", + }} + appResult, err := appClient.CallTool(ctx, args) + if err != nil || appResult.IsError { + t.Fatalf("app tool result = %#v, %v", appResult, err) + } + if len(appResult.Content) == 0 || appResult.StructuredContent == nil { + t.Fatal("app result must keep meaningful text and structured content") + } + text, ok := appResult.Content[0].(*mcp.TextContent) + if !ok || !strings.Contains(text.Text, "air_temp_c") { + t.Fatal("text fallback lost query data") + } + for _, capabilities := range []*mcp.ClientCapabilities{ + nil, {}, + {Extensions: map[string]any{appExtension: map[string]any{}}}, + {Extensions: map[string]any{appExtension: map[string]any{"mimeTypes": []string{"text/html"}}}}, + {Extensions: map[string]any{appExtension: map[string]any{"mimeTypes": "text/html;profile=mcp-app"}}}, + {Experimental: map[string]any{appExtension: map[string]any{"mimeTypes": []string{appMIMEType}}}}, + } { + cs := connectAppsClient(t, ctx, srv, capabilities) + plainTools, err := cs.ListTools(ctx, nil) + if err != nil { + t.Fatal(err) + } + if len(plainTools.Tools) != len(appTools.Tools) { + t.Fatal("text fallback changed tool availability") + } + for i, plain := range plainTools.Tools { + if _, ok := plain.Meta["ui"]; ok { + t.Errorf("UI metadata advertised without compatible capability: %#v", capabilities) + } + app := *appTools.Tools[i] + app.Meta = nil + if !reflect.DeepEqual(plain, &app) { + t.Errorf("text fallback changed definition of %s", plain.Name) + } + } + result, err := cs.CallTool(ctx, args) + if err != nil || !reflect.DeepEqual(result, appResult) { + t.Errorf("text fallback changed tool result: %#v, %v", result, err) + } + // Parallel listings must never strip the shared registered metadata. + var wg sync.WaitGroup + for _, session := range []*mcp.ClientSession{cs, appClient} { + wg.Go(func() { + listed, err := session.ListTools(ctx, nil) + if err != nil { + t.Error(err) + return + } + for _, tool := range listed.Tools { + _, hasUI := tool.Meta["ui"] + if hasUI != (session == appClient) { + t.Errorf("concurrent listing leaked capabilities for %s", tool.Name) + } + } + }) + } + wg.Wait() + } +} + +func TestSupportsApps(t *testing.T) { + for _, settings := range []any{nil, "bad", true, map[string]any{"mimeTypes": nil}, map[string]any{"mimeTypes": []any{42, map[string]any{}, "text/html"}}} { + if supportsApps(&mcp.ClientCapabilities{Extensions: map[string]any{appExtension: settings}}) { + t.Errorf("accepted malformed/unsupported UI capability %#v", settings) + } + } + if supportsApps(nil) || !supportsApps(appsClientCapabilities()) || !supportsApps(&mcp.ClientCapabilities{Extensions: map[string]any{ + appExtension: map[string]any{"mimeTypes": []any{"other", appMIMEType}}, + }}) { + t.Fatal("UI capability negotiation did not recognize supported MIME types") + } +} diff --git a/internal/mcpapp/archive.go b/internal/mcpapp/archive.go index 7778111..2615f18 100644 --- a/internal/mcpapp/archive.go +++ b/internal/mcpapp/archive.go @@ -111,7 +111,7 @@ type BackfillOut struct { // registers with any archive at all, keeping coverage visibility in read-only // deployments where the write tools below are absent. func registerArchiveStatusTool(srv *mcp.Server, st *store.Store) { - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "archive_status", Title: "Archive status", Description: "Return row count, coverage, newest-row age, backfill state, and the ten largest gaps. This operation is read-only.", diff --git a/internal/mcpapp/history.go b/internal/mcpapp/history.go index 8d08271..f43c061 100644 --- a/internal/mcpapp/history.go +++ b/internal/mcpapp/history.go @@ -309,7 +309,7 @@ func registerHistoryTools(srv *mcp.Server, st *store.Store) { } func registerCalendarTools(srv *mcp.Server, st *store.Store) { - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "this_day_in_history", Title: "This day in history", Description: "Return this calendar day for each archived year. Results include temperature (°F), rain (in), gusts (mph), and cross-year records. date accepts MM-DD or YYYY-MM-DD and defaults to today.", @@ -342,7 +342,7 @@ func registerCalendarTools(srv *mcp.Server, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "period_summary", Title: "Monthly / yearly summary", Description: "Group archive data by calendar month or year. Results include temperature (°F), rain (in), gusts (mph), observed days, and rainy days. The default range is the full archive.", @@ -372,7 +372,7 @@ func registerCalendarTools(srv *mcp.Server, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "wind_rose", Title: "Wind rose", Description: "Return wind distribution across 16 compass sectors. Each sector includes its share, mean speed, and peak gust in mph. The default range is the full archive.", @@ -396,7 +396,7 @@ func registerCalendarTools(srv *mcp.Server, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "get_observations", Title: "Observation series (downsampled)", Description: "Return a bounded, downsampled observation series. Values use °F, inHg, mph, and inches. The default range is 24 hours. max_points defaults to 288 and cannot exceed 2000.", @@ -446,7 +446,7 @@ func registerCalendarTools(srv *mcp.Server, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "climate_normals", Title: "Climate normals (12-month table)", Description: "Return archive averages for each calendar month. Results include temperature (°F), rain (in), rainy days, and the number of contributing years.", @@ -463,7 +463,7 @@ func registerCalendarTools(srv *mcp.Server, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "rain_stats", Title: "Rainfall statistics", Description: "Return rain totals, rainy days, the wettest day, and the longest dry and wet spells. Coverage gaps end a spell. The default range is the full archive.", @@ -489,7 +489,7 @@ func registerCalendarTools(srv *mcp.Server, st *store.Store) { } func registerClimateTools(srv *mcp.Server, st *store.Store) { - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "pressure_trend", Title: "Barometric tendency", Description: "Return the change in station pressure over a trailing window. The default is 3 hours. The accepted range is 1 second through 24 hours.", @@ -514,7 +514,7 @@ func registerClimateTools(srv *mcp.Server, st *store.Store) { return nil, PressureTrendOut{PressureTrend: *trend}, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "climate_indices", Title: "Climate threshold-day indices", Description: "Count frost, ice, summer, hot, and tropical-night days. Thresholds use °F and can be changed. The default range is the full archive. Set yearly to include annual counts.", @@ -551,7 +551,7 @@ func registerClimateTools(srv *mcp.Server, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "climatology", Title: "Typical day (hourly climatology)", Description: "Return conditions by local hour. Each hour includes temperature (°F), humidity, wind, and gusts (mph). The default range is the full archive.", @@ -575,7 +575,7 @@ func registerClimateTools(srv *mcp.Server, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "degree_days", Title: "Degree-days (heating / cooling / growing)", Description: "Calculate heating, cooling, and growing degree-days in °F-days. Heating and cooling bases default to 65°F. The growing base defaults to 50°F and its cap to 86°F. Set monthly for monthly results.", @@ -617,7 +617,7 @@ func registerClimateTools(srv *mcp.Server, st *store.Store) { } func registerSensorTools(srv *mcp.Server, st *store.Store) { - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "lightning_activity", Title: "Lightning activity", Description: "Return strike counts, storm days, distance, busiest day, and storm-free spells. Distances use miles. Coverage gaps end a spell. The default range is the full archive.", @@ -643,7 +643,7 @@ func registerSensorTools(srv *mcp.Server, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "solar_stats", Title: "Solar and UV statistics", Description: "Return solar, UV, illuminance, and insolation statistics. Insolation estimates use each solar reading's reported duration. The default range is the full archive.", @@ -669,7 +669,7 @@ func registerSensorTools(srv *mcp.Server, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "wind_stats", Title: "Wind speed statistics", Description: "Return mean wind, peak gust, peak sustained wind, the windiest day, and calm share. Speeds use mph. The default range is the full archive.", @@ -693,7 +693,7 @@ func registerSensorTools(srv *mcp.Server, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "comfort_stats", Title: "Human-comfort extremes", Description: "Return heat-index, wind-chill, and dew-point extremes in °F. Calculations use matching 15-minute sensor means; missing required readings omit the affected value. The default range is the full archive.", @@ -719,7 +719,7 @@ func registerSensorTools(srv *mcp.Server, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "sensor_health", Title: "Sensor health diagnostic", Description: "Return count, coverage, last reading, and stale state for continuous sensors. A sensor is stale after one hour. Results also include the battery range. The default range is the full archive.", @@ -743,7 +743,7 @@ func registerSensorTools(srv *mcp.Server, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "pressure_stats", Title: "Barometric pressure statistics", Description: "Return station-pressure mean, extremes, and daily changes in inHg. Changes compare consecutive observed days only. The default range is the full archive.", @@ -771,7 +771,7 @@ func registerSensorTools(srv *mcp.Server, st *store.Store) { } func registerTrendAndQueryTools(srv *mcp.Server, st *store.Store) { - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "temperature_spells", Title: "Heat waves and cold snaps", Description: "Return the longest heat wave and cold snap. Heat defaults to at least 90°F. Cold defaults to at most 32°F. Coverage gaps end a run.", @@ -795,7 +795,7 @@ func registerTrendAndQueryTools(srv *mcp.Server, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "temperature_trend", Title: "Warming / cooling trend", Description: "Fit a temperature trend from monthly anomalies across the full archive. Results include °F per decade, R², and the largest anomalies. A short archive returns no slope.", @@ -815,7 +815,7 @@ func registerTrendAndQueryTools(srv *mcp.Server, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "query_sql", Title: "Read-only SQL query", Description: "Run one SELECT or WITH SELECT against the read-only archive. Values use SI units. Query text is limited to 64 KiB. max_rows defaults to 100 and cannot exceed 1000.", diff --git a/internal/mcpapp/tools.go b/internal/mcpapp/tools.go index d6b8946..d142555 100644 --- a/internal/mcpapp/tools.go +++ b/internal/mcpapp/tools.go @@ -111,9 +111,10 @@ func appendOnlyWrite() *mcp.ToolAnnotations { // ---- tool registration ------------------------------------------------------ func registerTools(srv *mcp.Server, live *liveSource, st *store.Store) { + srv.AddReceivingMiddleware(appToolsMiddleware) // current_conditions: available whenever we have a live source or an archive. if live != nil || st != nil { - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "current_conditions", Title: "Current conditions", Description: "Return the latest conditions, preferring live data when available. An archive supplies fallback data; matching recent pressure history can add a normalized three-hour pressure rate.", @@ -157,7 +158,7 @@ func registerTools(srv *mcp.Server, live *liveSource, st *store.Store) { // Live tools: need the REST API (a token). if live != nil { - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "list_stations", Title: "List stations", Description: "List stations and devices available to the configured token. Results include location and timezone.", @@ -177,7 +178,7 @@ func registerTools(srv *mcp.Server, live *liveSource, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "forecast", Title: "Forecast", Description: "Return current, hourly, and daily forecast data. Temperature uses °F and wind uses mph. hours cannot exceed 240. days cannot exceed 10.", @@ -205,7 +206,7 @@ func registerTools(srv *mcp.Server, live *liveSource, st *store.Store) { return nil, buildForecast(s, f, hours, days), nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "station_details", Title: "Station details", Description: "Return station metadata, coordinates, elevation in meters, timezone, and connected devices.", @@ -232,7 +233,7 @@ func registerTools(srv *mcp.Server, live *liveSource, st *store.Store) { // Archive-backed history tools. if st != nil { - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "station_info", Title: "Station & archive info", Description: "Return archive coverage. Include live station metadata only when the archive's device belongs to that station.", @@ -263,7 +264,7 @@ func registerTools(srv *mcp.Server, live *liveSource, st *store.Store) { return nil, out, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "daily_summary", Title: "Daily summary", Description: "Return daily temperature in °F, rain in inches, and gusts in mph. days defaults to 7 and cannot exceed 366.", @@ -280,7 +281,7 @@ func registerTools(srv *mcp.Server, live *liveSource, st *store.Store) { return nil, DailySummaryOut{From: localDate(start), To: localDate(end), Days: days}, nil }) - mcp.AddTool(srv, &mcp.Tool{ + addAppTool(srv, &mcp.Tool{ Name: "records", Title: "All-time records", Description: "Return archive-wide temperature, wind, pressure, solar, UV, rain, and lightning records.", diff --git a/internal/mcpapp/ui/app.html b/internal/mcpapp/ui/app.html new file mode 100644 index 0000000..daf48c9 --- /dev/null +++ b/internal/mcpapp/ui/app.html @@ -0,0 +1,925 @@ + + + + + + + TempestKeep · Weather explorer + + + + +
+
+
TempestKeep
+ WEATHER EXPLORER + Connecting +
+
+

YOUR WEATHER, IN CONTEXT

Weather explorer

Waiting for your tool result.

+ +
+
Connecting to your MCP Apps host…
+
+
Powered by your Tempest dataRead-only view · No background polling
+
+ + + diff --git a/internal/mcpapp/ui/app.js b/internal/mcpapp/ui/app.js new file mode 100644 index 0000000..ba1b524 --- /dev/null +++ b/internal/mcpapp/ui/app.js @@ -0,0 +1,288 @@ +import { App, applyDocumentTheme, applyHostStyleVariables } from "@modelcontextprotocol/ext-apps"; +import { PAGE_SIZE, MAX_COLUMNS, number, object, text, pretty, label, unit, formatted, datasets, numericColumns, cell, compare, dateLabel, timeLabel } from "./data.js"; +import { seriesChart, windChart } from "./charts.js"; + +const TITLES = { + current_conditions: "Current conditions", get_observations: "Weather in detail", daily_summary: "Daily weather", forecast: "Weather ahead", query_sql: "Explore your archive", wind_rose: "Where the wind comes from", list_stations: "Your stations", station_details: "Station details", station_info: "Station & archive", archive_status: "Archive health", records: "Weather records", this_day_in_history: "This day, through the years", period_summary: "Weather over time", climate_normals: "The shape of your seasons", rain_stats: "Rainfall patterns", pressure_trend: "Pressure tendency", climate_indices: "Climate indices", climatology: "Your daily rhythm", degree_days: "Degree days", lightning_activity: "Lightning activity", solar_stats: "Sun & solar", wind_stats: "Wind patterns", comfort_stats: "How the weather feels", sensor_health: "Sensor health", pressure_stats: "Pressure patterns", temperature_spells: "Heat waves & cold snaps", temperature_trend: "Temperature trend", +}; +const tool = document.body.dataset.tool; +const validTool = Object.hasOwn(TITLES, tool); +const app = new App({ name: "TempestKeep Weather Explorer", version: __TEMPESTKEEP_VERSION__ }, {}); +const byId = (id) => document.getElementById(id); +const content = byId("content"), message = byId("message"), refresh = byId("refresh"); +const state = { data: null, tables: [], table: 0, search: "", sort: null, direction: 1, page: 0, metric: "", args: null, connected: false, busy: false, generation: 0 }; + +function el(tag, className, value) { + const node = document.createElement(tag); + if (className) node.className = className; + if (value !== undefined) node.textContent = String(value); + return node; +} +function button(value, className, callback) { + const node = el("button", className, value); + node.type = "button"; node.addEventListener("click", callback); + return node; +} +function status(value = "", error = false) { + message.textContent = value; + message.classList.toggle("error", error); + message.setAttribute("role", error ? "alert" : "status"); + content.setAttribute("aria-busy", String(state.busy)); +} +function updateRefresh() { + const supported = Boolean(app.getHostCapabilities()?.serverTools); + refresh.disabled = !validTool || !state.connected || !supported || !state.args || state.busy; + refresh.title = !supported ? "This host does not support refreshing server tools." : !state.args ? "Waiting for the original tool arguments." : "Run this read-only tool again with its original arguments."; +} +function hostContext(context) { + if (!context) return; + if (context.theme) applyDocumentTheme(context.theme); + if (context.styles?.variables) applyHostStyleVariables(context.styles.variables); + // External host fonts are deliberately not loaded; the resource has no network access. +} +function numberValue(value, key, sql = false) { + const node = el("span", "", formatted(value, key, sql)); + if (value != null && unit(key) && !sql) node.append(el("small", "", unit(key))); + return node; +} +function stat(labelText, value, key, note, hero = false) { + const item = el("div", hero ? "hero-stat" : "metric"); + item.append(el("div", hero ? "hero-label" : "metric-label", labelText)); + const valueNode = el("div", hero ? "hero-value" : "metric-value"); + valueNode.append(numberValue(value, key)); item.append(valueNode); + if (note) item.append(el("div", hero ? "hero-note" : "metric-note", note)); + return item; +} +function aggregate(rows, key, operation) { + const values = rows.map(row => row[key]).filter(number); + if (!values.length) return null; + if (operation === "sum") return values.reduce((sum, value) => sum + value, 0); + if (operation === "max") return Math.max(...values); + if (operation === "min") return Math.min(...values); + return values.reduce((sum, value) => sum + value, 0) / values.length; +} +function heroBlock(data, primary, rows) { + const hero = el("section", "hero"); hero.setAttribute("aria-label", "Weather overview"); + const main = el("div"); + const conditions = tool === "current_conditions" ? data : tool === "forecast" ? data.current : null; + const temperature = conditions ? conditions.temp_f : aggregate(rows, "temp_avg_f"); + if (tool === "query_sql") { + main.append(el("div", "hero-label", "A closer look at your data"), el("div", "hero-value", `${primary?.rows.length.toLocaleString() ?? 0} rows to explore`), el("div", "hero-note", "Search, sort, and discover patterns in your result.")); + hero.append(main, stat("Columns", primary?.columns.length ?? 0, "", "As selected by your query", true), stat("Result", data.truncated ? "Capped" : "Complete", "", data.truncated ? "More rows exist on the server" : "All returned rows available", true)); + } else if (conditions || temperature !== null) { + main.append(el("div", "hero-label", conditions ? conditions.conditions || "Latest reading" : "Average of returned readings")); + const value = el("div", "hero-value"); value.append(numberValue(temperature, "temp_f")); main.append(value); + main.append(el("div", "hero-note", conditions ? (data.station || (data.source === "archive" ? "From your local archive" : "From your Tempest station")) : `${rows.length.toLocaleString()} ${pretty(primary?.name ?? "readings")} · ${data.bucket_minutes ? `${data.bucket_minutes}-minute buckets` : "Archive weather"}`)); + hero.append(main, + stat(conditions ? "Feels like" : "Highest reading", conditions ? conditions.feels_like_f : aggregate(rows, "temp_max_f", "max"), "temp_f", conditions ? "Apparent temperature" : "In this returned series", true), + stat(conditions ? "Humidity" : "Lowest reading", conditions ? conditions.humidity_pct : aggregate(rows, "temp_min_f", "min"), conditions ? "humidity_pct" : "temp_f", conditions ? "Relative humidity" : "In this returned series", true)); + } else { + const total = object(data.total) ? data.total : data; + const fields = Object.entries(total).filter(([key, value]) => number(value) && !/epoch|(^|_)id$/.test(key)).slice(0, 3); + const [key, value] = fields[0] ?? ["Readings", primary?.rows.length ?? 0]; + main.append(el("div", "hero-label", label(key))); + const big = el("div", "hero-value"); big.append(numberValue(value, key)); main.append(big, el("div", "hero-note", "From the returned tool result")); hero.append(main); + fields.slice(1).forEach(([field, val]) => hero.append(stat(label(field), val, field, "", true))); + } + return hero; +} +function metricCards(data, rows) { + const cards = el("section", "metrics"); cards.setAttribute("aria-label", "Summary metrics"); + if (tool === "query_sql") return cards; + const conditions = tool === "current_conditions"; + const series = rows.some(row => Object.hasOwn(row, "temp_avg_f") || Object.hasOwn(row, "temp_f")); + if (conditions || series) { + const windKey = rows.some(row => Object.hasOwn(row, "peak_gust_mph")) ? "peak_gust_mph" : "gust_mph"; + const entries = conditions ? [ + ["Wind speed", data.wind_mph, "wind_mph", data.wind_dir || "Reported average"], ["Wind gust", data.gust_mph, "gust_mph", "Latest observation"], ["Rain today", data.rain_today_in, "rain_today_in", "Local calendar day"], ["Pressure", data.pressure_inhg, "pressure_inhg", data.pressure_trend || "Reported pressure"], + ] : [ + ["Rainfall", aggregate(rows, "rain_in", "sum"), "rain_in", "Total in returned rows"], ["Peak gust", aggregate(rows, windKey, "max"), "gust_mph", "Highest returned reading"], ["Humidity", aggregate(rows, "humidity_pct"), "humidity_pct", "Average of returned readings"], ["Observations", aggregate(rows, "obs", "sum"), "obs", "Contributing samples"], + ]; + // Forecasts have no rainfall totals or observation counts; show forecast data. + if (tool === "forecast") entries.splice(0, entries.length, + ["Rain chance", aggregate(rows, "precip_probability", "max"), "precip_probability", "Highest hourly probability"], ["Peak gust", aggregate(rows, "gust_mph", "max"), "gust_mph", "Hourly forecast maximum"], ["Wind speed", aggregate(rows, "wind_mph"), "wind_mph", "Average hourly forecast"], ["Hourly outlook", rows.length, "", "Hours returned"]); + entries.forEach(args => cards.append(stat(...args))); + } + return cards; +} +function chartPanel(table) { + const columns = numericColumns(table); + if (!columns.length || !table.rows.length || table.name === "sectors" || ["stations", "devices", "gaps"].includes(table.name)) return null; + if (!columns.some(column => column.key === state.metric)) state.metric = columns.find(column => ["temp_avg_f", "temp_f", "high_f", "coverage_pct"].includes(column.key))?.key ?? columns[0].key; + const panel = el("section", "panel"); panel.id = "chart-panel"; + const head = el("div", "panel-head"), title = el("div"); + title.append(el("h2", "", label(state.metric)), el("p", "panel-description", `${table.rows.length.toLocaleString()} returned readings · ${unit(state.metric) || "Reported values"}`)); + const select = el("select", "metric-select"); select.id = "metric"; select.setAttribute("aria-label", "Chart metric"); + columns.forEach(column => { const option = el("option", "", column.title); option.value = column.key; select.append(option); }); select.value = state.metric; + select.addEventListener("change", () => { state.metric = select.value; const replacement = chartPanel(table); panel.replaceWith(replacement); replacement.querySelector("select").focus(); }); + head.append(title, select); panel.append(head); + const wrap = el("div", "chart-wrap"); wrap.append(seriesChart(table.rows, state.metric, tool === "get_observations" ? state.data.bucket_minutes : 0)); panel.append(wrap); + const foot = el("div", "chart-footer"); foot.append(el("span", "legend", label(state.metric)), el("span", "", table.rows.length <= 60 ? "Missing values leave gaps · Hover points for readings" : "Missing values leave gaps · Exact readings in the table")); panel.append(foot); + return panel; +} +function windPanel(data, table) { + const panel = el("section", "panel"); panel.id = "chart-panel"; + const head = el("div", "panel-head"); head.append(el("h2", "", "Wind direction frequency"), el("span", "badge", "16 compass sectors")); panel.append(head); + const wrap = el("div", "wind-layout"); wrap.append(windChart(table.rows.slice(0, 16))); + const strongest = table.rows.filter(row => number(row.pct) && row.pct > 0).reduce((best, row) => !best || row.pct > best.pct ? row : best, null); + const note = el("div", "wind-note"); + note.append(el("div", "eyebrow", "Most frequent direction"), el("h3", "", strongest ? `${strongest.sector} · ${formatted(strongest.pct)}%` : "No directional readings"), el("p", "", `${formatted(data.calm_pct)}% calm below ${formatted(data.calm_threshold_mph)} mph.`), el("p", "", "Wedge area shows the share of directional observations. Exact frequencies and speeds are in the table.")); + wrap.append(note); panel.append(wrap); return panel; +} +function tablePanel() { + const table = state.tables[state.table]; + const panel = el("section", "panel"); panel.id = "data-panel"; + const head = el("div", "panel-head"), title = el("div"); + title.append(el("h2", "", tool === "query_sql" ? "Query results" : "Explore the readings"), el("p", "panel-description", table.sql ? "Original column names and values · Units follow your SELECT" : "Click a column to sort · Search across all returned rows")); + head.append(title, el("span", "badge", `${table.rows.length.toLocaleString()} rows`)); panel.append(head); + const tools = el("div", "table-tools"), tabs = el("div", "tabs"); + tabs.setAttribute("aria-label", "Datasets"); + state.tables.forEach((dataset, i) => { + const tab = button(pretty(dataset.name), "tab", () => { + state.table = i; state.page = 0; state.search = ""; state.sort = null; state.metric = ""; render(); + }); tab.setAttribute("aria-pressed", String(i === state.table)); tabs.append(tab); + }); + const searchWrap = el("label", "search-wrap"); searchWrap.append(el("span", "sr-only", "Search rows")); + const search = el("input", "search"); search.id = "search"; search.type = "search"; search.placeholder = "Search readings…"; search.value = state.search; search.maxLength = 200; + search.addEventListener("input", () => { state.search = search.value; state.page = 0; renderRows(); }); searchWrap.append(search); tools.append(tabs, searchWrap); panel.append(tools); + const scroll = el("div", "table-scroll"); scroll.tabIndex = 0; scroll.setAttribute("role", "region"); scroll.setAttribute("aria-label", "Scrollable data table"); + const grid = el("table"); grid.id = "data-table"; + const caption = el("caption", "sr-only", `${TITLES[tool]}: ${pretty(table.name)}. Missing values are shown as an em dash.`); grid.append(caption); + const thead = el("thead"), tr = el("tr"); + table.columns.forEach((column, index) => { + const th = el("th"); th.scope = "col"; + if (table.rows.some(row => number(cell(row, column)))) th.className = "numeric"; + th.setAttribute("aria-sort", state.sort === index ? state.direction === 1 ? "ascending" : "descending" : "none"); + th.append(button(column.title, "", () => { + state.direction = state.sort === index ? -state.direction : 1; state.sort = index; state.page = 0; + [...thead.querySelectorAll("th")].forEach((node, i) => node.setAttribute("aria-sort", state.sort === i ? state.direction === 1 ? "ascending" : "descending" : "none")); renderRows(); + })); tr.append(th); + }); thead.append(tr); grid.append(thead, el("tbody")); scroll.append(grid); panel.append(scroll); + const bottom = el("div", "table-bottom"), info = el("span"); info.id = "row-count"; info.setAttribute("aria-live", "polite"); + const pagination = el("div", "pagination"), pageInfo = el("span"); pageInfo.id = "page-info"; + const previous = button("‹", "button", () => { state.page--; renderRows(); }); previous.id = "previous"; previous.setAttribute("aria-label", "Previous page"); + const next = button("›", "button", () => { state.page++; renderRows(); }); next.id = "next"; next.setAttribute("aria-label", "Next page"); + pagination.append(previous, pageInfo, next); bottom.append(info, pagination); panel.append(bottom); + if (table.limited) panel.append(el("p", "note", "Display limited to 2,000 rows and 64 columns. Narrow the tool request to inspect more.")); + return panel; +} +function renderRows() { + const table = state.tables[state.table]; + if (!table) return; + const query = state.search.trim().toLocaleLowerCase(); + const rows = table.rows.filter(row => !query || table.columns.some(column => formatted(cell(row, column), column.raw, table.sql).toLocaleLowerCase().includes(query))); + if (state.sort !== null) { const column = table.columns[state.sort]; rows.sort((a, b) => compare(cell(a, column), cell(b, column), state.direction)); } + const pages = Math.max(1, Math.ceil(rows.length / PAGE_SIZE)); state.page = Math.max(0, Math.min(state.page, pages - 1)); + const body = byId("data-table").querySelector("tbody"); body.replaceChildren(); + for (const row of rows.slice(state.page * PAGE_SIZE, (state.page + 1) * PAGE_SIZE)) { + const tr = el("tr"); + table.columns.forEach(column => { + const value = cell(row, column), td = el("td", number(value) ? "numeric" : value == null ? "null" : "", formatted(value, column.raw, table.sql)); + td.title = value == null ? "Missing reading" : text(value); tr.append(td); + }); body.append(tr); + } + if (!rows.length) { const tr = el("tr"), td = el("td", "empty", query ? "No rows match your search." : "No readings returned for this range."); td.colSpan = Math.max(1, table.columns.length); tr.append(td); body.append(tr); } + byId("row-count").textContent = rows.length ? `${state.page * PAGE_SIZE + 1}–${Math.min((state.page + 1) * PAGE_SIZE, rows.length)} of ${rows.length.toLocaleString()} rows${query ? ` · ${table.rows.length} before filtering` : ""}` : "0 rows"; + byId("page-info").textContent = `${state.page + 1} / ${pages}`; + byId("previous").disabled = state.page === 0; byId("next").disabled = state.page >= pages - 1; +} +function detailsPanel(data) { + const entries = Object.entries(data).slice(0, MAX_COLUMNS).flatMap(([key, value]) => { + if (Array.isArray(value) || key === "note") return []; + if (object(value)) return Object.entries(value).slice(0, MAX_COLUMNS).filter(([, item]) => !object(item) && !Array.isArray(item)).map(([field, item]) => [`${key}.${field}`, field, item]); + return [[key, key, value]]; + }).slice(0, 128); + if (!entries.length) return null; + const details = el("details", "panel details"); details.id = "result-details"; + details.open = state.tables.length === 0; + details.append(el("summary", "", `Result details · ${entries.length} fields`)); + const list = el("dl"); + for (const [name, key, value] of entries) { list.append(el("dt", "", pretty(name)), el("dd", value == null ? "null" : "", `${formatted(value, key)}${value != null && unit(key) ? ` ${unit(key)}` : ""}`)); } + details.append(list); return details; +} +function render() { + const data = state.data; if (!data) return; + const table = state.tables[state.table], rows = table?.sql ? [] : table?.rows ?? []; + byId("subtitle").textContent = data.from || data.to ? `${timeLabel(data.from ?? "Archive start")} — ${timeLabel(data.to ?? "Latest reading")}` : data.station || data.name || (data.time ? timeLabel(data.time) : "Your tool result, ready to explore."); + byId("eyebrow").textContent = tool === "query_sql" ? "YOUR ARCHIVE, YOUR QUESTIONS" : tool === "forecast" ? "A LOOK AT WHAT'S AHEAD" : "YOUR WEATHER, IN CONTEXT"; + content.replaceChildren(heroBlock(data, table, rows)); + const cards = metricCards(data, rows); if (cards.childElementCount) content.append(cards); + if (table) { const chart = tool === "wind_rose" && table.name === "sectors" ? windPanel(data, table) : chartPanel(table); if (chart) content.append(chart); content.append(tablePanel()); renderRows(); } + if (data.truncated === true) content.append(el("p", "note", "Result truncated by the server. Search and pagination cover returned rows only. Narrow the query or increase max_rows within the server limit to see more.")); + if (typeof data.note === "string" && data.note) content.append(el("p", "note", text(data.note))); + const details = detailsPanel(data); if (details) content.append(details); + content.setAttribute("aria-busy", String(state.busy)); +} +function receiveResult(result, preservePrevious = false) { + state.busy = false; + try { + if (result.isError) { + const detail = result.content?.find(item => item.type === "text")?.text; + throw new Error(detail ? text(detail, 500) : "The tool could not complete this request."); + } + let data = result.structuredContent; + if (data == null) { + const source = result.content?.find(item => item.type === "text")?.text; + if (typeof source !== "string" || source.length > 2_000_000) throw new Error("No supported weather data was returned."); + data = JSON.parse(source); + } + if (!object(data)) throw new Error("The tool result is not a supported data object."); + state.data = data; state.tables = datasets(data); state.table = tool === "forecast" ? Math.max(0, state.tables.findIndex(table => table.name === "hourly")) : 0; state.page = 0; state.search = ""; state.sort = null; + render(); status(); + } catch (error) { + if (!preservePrevious) { content.replaceChildren(); state.data = null; state.tables = []; } + const detail = error instanceof SyntaxError ? "The tool returned invalid JSON. Run the tool again to retry." : text(error.message, 500); + status(`${detail}${preservePrevious && state.data ? " The previous result is still shown." : ""}`, true); + } + updateRefresh(); +} + +// Install every handler before connect: hosts can deliver input/results as soon +// as the handshake completes. No tools are called until the user hits Refresh. +app.ontoolinput = ({ arguments: args }) => { + state.generation++; + state.args = object(args) ? structuredClone(args) : args === undefined && tool !== "query_sql" ? {} : null; + state.busy = true; content.replaceChildren(); state.data = null; + status("Loading your weather data…"); updateRefresh(); +}; +app.ontoolresult = (result) => { state.generation++; receiveResult(result); }; +app.ontoolcancelled = () => { state.generation++; state.busy = false; content.replaceChildren(); state.data = null; status("This tool request was cancelled. Refresh to try again."); updateRefresh(); }; +app.onhostcontextchanged = hostContext; +app.onerror = () => { state.busy = false; status("The host connection encountered an error. Run the tool again if the view does not recover.", true); updateRefresh(); }; +app.onclose = () => { state.generation++; state.connected = false; state.busy = false; byId("connection").textContent = "Host disconnected"; status("The host disconnected. Run this tool again to reconnect.", true); updateRefresh(); }; +app.onteardown = async () => { state.generation++; state.connected = false; updateRefresh(); return {}; }; +let resizeFrame = 0; +window.addEventListener("resize", () => { + cancelAnimationFrame(resizeFrame); + resizeFrame = requestAnimationFrame(() => { + const table = state.tables[state.table], old = byId("chart-panel"); + if (!old || !table || tool === "wind_rose") return; + const replacement = chartPanel(table); + if (replacement) old.replaceWith(replacement); + }); +}); +refresh.addEventListener("click", async () => { + if (refresh.disabled) return; + const generation = ++state.generation; + state.busy = true; status("Refreshing your tool result…"); updateRefresh(); + try { + const result = await app.callServerTool({ name: tool, arguments: structuredClone(state.args) }, { timeout: 30000 }); + if (generation === state.generation) receiveResult(result, true); + } catch { + if (generation !== state.generation) return; + state.busy = false; status("Refresh failed. The previous result is still shown; try again when the host is ready.", true); updateRefresh(); + } +}); +byId("title").textContent = validTool ? TITLES[tool] : "Weather explorer"; +if (!validTool) { + status("Open this view from a TempestKeep tool in an MCP Apps-capable host.", true); +} else { + app.connect(undefined, { timeout: 15000 }).then(() => { + state.connected = true; hostContext(app.getHostContext()); + byId("connection").textContent = "Connected to your host"; updateRefresh(); + if (!state.data && !state.busy) status("Ready. Waiting for your tool result…"); + }).catch(() => { + state.busy = false; byId("connection").textContent = "Host unavailable"; + status("Connect through an MCP Apps-capable host, then run this TempestKeep tool again.", true); updateRefresh(); + }); +} diff --git a/internal/mcpapp/ui/charts.js b/internal/mcpapp/ui/charts.js new file mode 100644 index 0000000..9b8d9a1 --- /dev/null +++ b/internal/mcpapp/ui/charts.js @@ -0,0 +1,107 @@ +import { number, formatted, label, unit, dateLabel, timeLabel } from "./data.js"; + +const NS = "http://www.w3.org/2000/svg"; +export function svg(tag, attributes = {}, value) { + const node = document.createElementNS(NS, tag); + for (const [key, val] of Object.entries(attributes)) node.setAttribute(key, String(val)); + if (value !== undefined) node.textContent = String(value); + return node; +} +export function seriesChart(rows, key, bucketMinutes = 0) { + const viewport = document.documentElement.clientWidth; + const mobile = viewport <= 480; + const width = Math.max(240, Math.min(1000, viewport - (mobile ? 38 : viewport <= 740 ? 62 : 114))); + const height = mobile ? 180 : 220; + const chart = svg("svg", { viewBox: `0 0 ${width} ${height}`, role: "img", "aria-label": `${label(key)} chart; exact readings in the table below`, class: "chart", preserveAspectRatio: "none" }); + const values = rows.map(row => row[key]).filter(number); + if (!values.length) return chart; + let low = Math.min(...values), high = Math.max(...values); + const bars = /rain|precip|strikes|degree_days|_days$|coverage/.test(key); + if (bars) low = Math.min(0, low); + const span = high - low || Math.abs(high) * .1 || 1; + low -= bars ? 0 : span * .18; + high += span * .18; + const left = mobile ? 38 : 48, right = width - 16, top = 20, bottom = height - 43; + const y = (value) => bottom - (value - low) / (high - low) * (bottom - top); + const times = rows.map(row => number(row.epoch) ? row.epoch * 1000 : typeof (row.time ?? row.day ?? row.date ?? row.period) === "string" ? Date.parse(row.time ?? row.day ?? row.date ?? row.period) : NaN); + const realTime = times.every(number) && times.at(-1) > times[0] && times.every((value, i) => !i || value >= times[i - 1]); + const x = (i) => rows.length === 1 ? (left + right) / 2 : left + (realTime ? (times[i] - times[0]) / (times.at(-1) - times[0]) : i / (rows.length - 1)) * (right - left); + for (let i = 0; i <= 3; i++) { + const value = low + (high - low) * i / 3; + chart.append(svg("line", { x1: left, x2: right, y1: y(value), y2: y(value), class: "chart-grid" })); + chart.append(svg("text", { x: left - 12, y: y(value) + 3, "text-anchor": "end" }, formatted(value, key))); + } + // Up to 2,000 points are returned by the server. Null samples break paths. + // Fills use separate segments so absent readings never look like zero. + const segments = []; + let segment = []; + rows.forEach((row, i) => { + // Archive series omit completely empty buckets. A known bucket width lets + // us break at those outages without inventing readings or calendar spacing. + if (i && bucketMinutes > 0 && number(times[i]) && number(times[i - 1]) && times[i] - times[i - 1] > bucketMinutes * 60000) { + if (segment.length) segments.push(segment); + segment = []; + } + if (!number(row[key])) { + if (segment.length) segments.push(segment); + segment = []; + } else segment.push([x(i), y(row[key]), i]); + }); + if (segment.length) segments.push(segment); + if (bars) { + const width = Math.max(.5, Math.min(24, (right - left) / Math.max(rows.length, 1) * .65)); + rows.forEach((row, i) => { + if (!number(row[key])) return; + const bar = svg("rect", { x: x(i) - width / 2, y: Math.min(y(row[key]), y(0)), width, height: Math.max(.5, Math.abs(y(row[key]) - y(0))), rx: 2, class: "chart-bar" }); + bar.append(svg("title", {}, `${row.time ? timeLabel(row.time) : dateLabel(row)}: ${formatted(row[key], key)} ${unit(key)}`)); + chart.append(bar); + }); + } else { + const defs = svg("defs"); + const gradient = svg("linearGradient", { id: "chart-fill", x1: 0, y1: 0, x2: 0, y2: 1 }); + gradient.append(svg("stop", { offset: "0%", "stop-color": "var(--accent)", "stop-opacity": ".15" }), svg("stop", { offset: "100%", "stop-color": "var(--accent)", "stop-opacity": ".015" })); + defs.append(gradient); chart.append(defs); + for (const points of segments) { + const line = points.map(([px, py], index) => `${index ? "L" : "M"}${px.toFixed(2)},${py.toFixed(2)}`).join(" "); + if (points.length > 1) chart.append(svg("path", { d: `${line} L${points.at(-1)[0]},${bottom} L${points[0][0]},${bottom}Z`, fill: "url(#chart-fill)" })); + chart.append(svg("path", { d: line, class: "chart-line" })); + if (rows.length <= 60 || points.length === 1) { + for (const [px, py, i] of points) { + const point = svg("circle", { cx: px, cy: py, r: 2.5, class: "chart-dot" }); + point.append(svg("title", {}, `${rows[i].time ? timeLabel(rows[i].time) : dateLabel(rows[i])}: ${formatted(rows[i][key], key)} ${unit(key)}`)); + chart.append(point); + } + } + } + } + const tickCount = Math.min(mobile ? 3 : 6, rows.length); + const ticks = [...new Set(Array.from({ length: tickCount }, (_, i) => Math.round(i * (rows.length - 1) / Math.max(1, tickCount - 1))))]; + const spansDates = typeof rows[0]?.time === "string" && rows[0].time.slice(0, 10) !== rows.at(-1)?.time?.slice(0, 10); + ticks.forEach((i, n) => chart.append(svg("text", { x: x(i), y: height - 13, "text-anchor": n === 0 ? "start" : n === ticks.length - 1 ? "end" : "middle" }, spansDates && typeof rows[i].time === "string" ? `${rows[i].time.slice(5, 10)} ${dateLabel(rows[i])}` : dateLabel(rows[i])))); + return chart; +} + +export function windChart(sectors) { + const chart = svg("svg", { viewBox: "0 0 320 280", role: "img", "aria-label": "Wind direction frequency; percentages are in the table below", class: "chart wind-chart" }); + const cx = 160, cy = 139, radius = 99; + const maximum = Math.max(...sectors.map(row => number(row.pct) ? row.pct : 0), 1); + for (let ring = 1; ring <= 4; ring++) chart.append(svg("circle", { cx, cy, r: radius * ring / 4, fill: "none", class: "chart-grid" })); + const directions = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]; + const polar = (angle, r) => [cx + Math.sin(angle) * r, cy - Math.cos(angle) * r]; + directions.forEach((direction, i) => { + const angle = i * Math.PI / 8; + const row = sectors.find(sector => sector.sector === direction); + if (row && number(row.pct) && row.pct > 0) { + const r = Math.sqrt(row.pct / maximum) * radius; + const a = polar(angle - Math.PI / 19, r), b = polar(angle + Math.PI / 19, r); + const wedge = svg("path", { d: `M${cx},${cy} L${a} A${r},${r} 0 0 1 ${b}Z`, fill: "var(--accent)", opacity: .55 + .4 * row.pct / maximum }); + wedge.append(svg("title", {}, `${direction}: ${formatted(row.pct)}%`)); chart.append(wedge); + } + if (i % 2 === 0) { + const [x, y] = polar(angle, 121); + chart.append(svg("text", { x, y: y + 3, "text-anchor": "middle" }, direction)); + } + }); + chart.append(svg("circle", { cx, cy, r: 7, fill: "var(--surface)" })); + return chart; +} diff --git a/internal/mcpapp/ui/data.js b/internal/mcpapp/ui/data.js new file mode 100644 index 0000000..d751c39 --- /dev/null +++ b/internal/mcpapp/ui/data.js @@ -0,0 +1,80 @@ +// All display limits apply before DOM allocation. Query columns remain positional: +// SQL permits duplicate names and names such as "__proto__". +export const MAX_ROWS = 2000; +export const MAX_COLUMNS = 64; +export const PAGE_SIZE = 8; +export const number = (value) => typeof value === "number" && Number.isFinite(value); +export const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value); +export const text = (value, limit = 2048) => { + if (value == null) return "—"; + if (typeof value === "string") return value.length > limit ? `${value.slice(0, limit)}…` : value; + if (typeof value === "boolean") return value ? "Yes" : "No"; + if (number(value)) return String(value); + // Nested values are described without traversing arbitrary object graphs. + if (Array.isArray(value)) return `${value.length.toLocaleString()} items`; + return object(value) ? "Nested object" : "—"; +}; +export const pretty = (key) => text(key, 100).replace(/_/g, " ").replace(/\buv\b/gi, "UV").replace(/\bsql\b/gi, "SQL"); + +const units = { precip_probability: "%", pct: "%", uv: "index", uv_max: "index", peak_uv: "index", change_mb_per_3h: "mb / 3h", slope_per_decade_f: "°F / decade", pressure_trend_3h_inhg: "inHg / 3h", heating_degree_days: "°F·days", cooling_degree_days: "°F·days", growing_degree_days: "°F·days", total_in: "in" }; +export function unit(key) { + if (Object.hasOwn(units, key)) return units[key]; + for (const [suffix, label] of [["_f", "°F"], ["_c", "°C"], ["_pct", "%"], ["_inhg", "inHg"], ["_mph", "mph"], ["_in", "in"], ["_wm2", "W/m²"], ["_mj", "MJ/m²"], ["_lux", "lux"], ["_mi", "mi"], ["_seconds", "s"], ["_hours", "h"], ["_v", "V"], ["_m", "m"]]) { + if (key.endsWith(suffix)) return label; + } + return ""; +} +const names = { temp_avg_f: "Average temperature", temp_min_f: "Low temperature", temp_max_f: "High temperature", temp_f: "Temperature", high_f: "High temperature", low_f: "Low temperature", humidity_pct: "Humidity", rain_in: "Rainfall", rain_today_in: "Rain today", wind_mph: "Wind speed", gust_mph: "Wind gust", peak_gust_mph: "Peak gust", pressure_inhg: "Pressure", obs: "Observations", solar_avg_wm2: "Solar radiation", solar_wm2: "Solar radiation", uv_max: "UV index", uv: "UV index", precip_probability: "Rain chance", pct: "Share", avg_mph: "Average speed", count: "Readings", coverage_pct: "Coverage" }; +export function label(key) { + if (Object.hasOwn(names, key)) return names[key]; + const base = key.replace(/_(f|c|pct|inhg|mph|in|wm2|mj|lux|mi|v)$/, ""); + const name = pretty(base); + return name.charAt(0).toUpperCase() + name.slice(1); +} +export function formatted(value, key = "", sql = false) { + if (!number(value)) return text(value); + if (sql) return String(value); // Do not round arbitrary SQL precision or infer units. + const precision = /inhg|rain|_in$/.test(key) ? 3 : 2; + return value.toLocaleString("en-US", { maximumFractionDigits: precision }); +} +export function datasets(data) { + if (Array.isArray(data.columns) && Array.isArray(data.rows)) { + const columns = data.columns.slice(0, MAX_COLUMNS).map((key, index) => ({ key: String(index), title: text(key, 160), raw: text(key, 160) })); + return [{ name: "Results", columns, rows: data.rows.slice(0, MAX_ROWS).filter(Array.isArray).map(row => row.slice(0, MAX_COLUMNS)), limited: data.rows.length > MAX_ROWS || data.columns.length > MAX_COLUMNS, sql: true }]; + } + const tables = []; + for (const [name, value] of Object.entries(data).slice(0, MAX_COLUMNS)) { + if (!Array.isArray(value)) continue; + const rows = value.slice(0, MAX_ROWS).filter(object); + const keys = [...new Set(rows.flatMap(row => Object.keys(row).slice(0, MAX_COLUMNS)))]; + const displayKeys = keys.includes("epoch") && keys.some(key => ["time", "day", "date"].includes(key)) ? [...keys.filter(key => key !== "epoch"), "epoch"] : keys; + const columns = displayKeys.slice(0, MAX_COLUMNS).map(key => ({ key, title: `${label(key)}${unit(key) ? ` (${unit(key)})` : ""}`, raw: key })); + tables.push({ name, columns, rows, limited: value.length > MAX_ROWS || keys.length > MAX_COLUMNS, sql: false }); + } + return tables; +} +export function cell(row, column) { + return Array.isArray(row) ? row[Number(column.key)] : Object.hasOwn(row, column.key) ? row[column.key] : null; +} +export function numericColumns(table) { + if (!table || table.sql) return []; + return table.columns.filter(column => !/epoch|(^|_)id$|^(year|month|hour|count|obs|observations|years)$/.test(column.key) && table.rows.some(row => number(cell(row, column)))); +} +export function dateLabel(row) { + if (row.hour != null) return `${String(row.hour).padStart(2, "0")}:00`; + const value = row.time ?? row.day ?? row.date ?? row.period ?? row.month_name ?? row.year ?? row.sector ?? row.sensor; + if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}T/.test(value)) return value.slice(11, 16); + return text(value, 30); +} +export function timeLabel(value) { + if (typeof value !== "string") return text(value, 80); + // Keep the tool's local calendar date and timezone; browser timezone may differ. + return value.replace("T", " · "); +} +export function compare(a, b, direction) { + // Missing readings always sort last and remain distinct from measured zero. + if (a == null) return b == null ? 0 : 1; + if (b == null) return -1; + if (number(a) && number(b)) return direction * (a - b); + return direction * text(a).localeCompare(text(b), "en", { numeric: true }); +} diff --git a/internal/mcpapp/ui/style.css b/internal/mcpapp/ui/style.css new file mode 100644 index 0000000..2c2ec99 --- /dev/null +++ b/internal/mcpapp/ui/style.css @@ -0,0 +1,6 @@ +:root{color-scheme:light;--page:#f5f5f0;--surface:#fff;--soft:#f6f7f3;--ink:#253b36;--muted:#64756e;--border:#e0e6de;--accent:#277b62;--accent-soft:#e9f2eb;--hero:#173e33;--hero-ink:#fff;--gold:#d1ac64;--shadow:0 3px 16px #1c3b2a03;font-family:var(--font-sans,Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif);font-synthesis:none} +:root[data-theme=dark]{color-scheme:dark;--page:#15231f;--surface:#1d2f29;--soft:#243a31;--ink:#ecf2ed;--muted:#adc0b4;--border:#3a5144;--accent:#88d4b4;--accent-soft:#2c4b3d;--hero:#102e25;--hero-ink:#f2f6f1;--gold:#e5bc78;--shadow:none} +*{box-sizing:border-box}body{margin:0;background:var(--page);color:var(--ink);font-size:14px;line-height:1.5}button,input,select{font:inherit}button,select{cursor:pointer}button:disabled{cursor:default;opacity:.48}button,input,select{color:var(--ink)}button:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible,a:focus-visible{outline:3px solid var(--accent);outline-offset:3px}button{touch-action:manipulation}#app{max-width:1240px;margin:auto;padding:0 36px 20px}.topbar{min-height:76px;display:flex;align-items:center;border-bottom:1px solid var(--border);gap:24px}.brand{display:flex;align-items:center;gap:10px;font-size:21px;letter-spacing:-.8px;font-weight:740}.brand-light{font-weight:450}.brand-icon{display:grid;place-items:center;width:30px;height:30px;color:var(--accent);font-size:35px}.edition{font-size:10px;color:var(--muted);letter-spacing:1.7px;border-left:1px solid var(--border);padding-left:24px}.connection{margin-left:auto;font-size:11px;display:flex;align-items:center;gap:7px;color:var(--muted)}.connection:before,.footer-dot{content:"";display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent)}.heading{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:28px 0 23px}.eyebrow{margin:0 0 5px;font-size:10px;letter-spacing:1.9px;font-weight:700;color:var(--accent)}h1{font-size:30px;line-height:1.15;letter-spacing:-1px;margin:0;font-weight:650}.subtitle{margin:8px 0 0;color:var(--muted);font-size:12px;overflow-wrap:anywhere}.button{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:36px;border:1px solid var(--border);border-radius:7px;padding:6px 13px;background:var(--surface);font-size:12px;font-weight:600;white-space:nowrap}.button:hover:not(:disabled){border-color:var(--accent);background:var(--accent-soft)}.button>span{font-size:19px;line-height:1}.message{border:1px solid var(--border);background:var(--surface);border-radius:12px;padding:28px;color:var(--muted);margin-bottom:20px}.message.error{border-color:#b87160;color:var(--ink)}.message:empty{display:none}.hero{background:var(--hero);color:var(--hero-ink);border-radius:14px;padding:24px 28px;display:grid;grid-template-columns:minmax(0,1.5fr) 1fr 1fr;align-items:center;gap:30px;margin-bottom:18px;position:relative;overflow:hidden}.hero:before{content:"";position:absolute;right:-25px;top:-100px;width:350px;height:350px;border:1px solid #fff09;border-radius:50%;pointer-events:none}.hero:after{content:"";position:absolute;right:-90px;top:-130px;width:470px;height:470px;border:1px solid #ffffff08;border-radius:50%;pointer-events:none}.hero-label{font-size:10px;letter-spacing:1.6px;text-transform:uppercase;color:#bad2c5;margin-bottom:8px}.hero-value{font-size:36px;font-weight:550;letter-spacing:-1.5px;line-height:1.2;overflow-wrap:anywhere}.hero-value small{font-size:17px;color:#cadacf;font-weight:400;margin-left:5px;letter-spacing:0}.hero-note{font-size:11px;color:#bed2c5;margin-top:8px;overflow-wrap:anywhere}.hero-stat{border-left:1px solid #ffffff22;padding-left:26px}.hero-stat .hero-value{font-size:26px;letter-spacing:-.7px}.metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px;margin-bottom:18px}.metric{border:1px solid var(--border);background:var(--surface);box-shadow:var(--shadow);border-radius:10px;padding:17px 19px;min-width:0}.metric-label{font-size:11px;color:var(--muted);margin-bottom:9px;display:flex;align-items:center;gap:7px}.metric-label:before{content:"";width:6px;height:6px;flex-shrink:0;border-radius:2px;background:var(--accent)}.metric:nth-child(2) .metric-label:before{background:#b49860}.metric:nth-child(3) .metric-label:before{background:#7b9aaa}.metric:nth-child(4) .metric-label:before{background:#aab19a}.metric-value{font-size:27px;font-weight:560;letter-spacing:-.8px;line-height:1.15;overflow-wrap:anywhere}.metric-value small{font-size:13px;font-weight:400;letter-spacing:0;margin-left:5px;color:var(--muted)}.metric-note{font-size:10px;margin-top:7px;color:var(--muted)}.panel{border:1px solid var(--border);background:var(--surface);border-radius:12px;box-shadow:var(--shadow);margin-bottom:18px;overflow:hidden}.panel-head{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:20px 22px 0}.panel h2{font-size:15px;line-height:1.3;margin:0;font-weight:600;letter-spacing:-.25px}.panel-description{font-size:11px;color:var(--muted);margin:5px 0 0}.metric-select{background:var(--soft);border:1px solid var(--border);border-radius:6px;font-size:11px;padding:7px 26px 7px 10px;max-width:220px}.chart-wrap{padding:12px 20px 0;position:relative}.chart{display:block;width:100%;height:220px;overflow:visible}.chart text{font-family:inherit;font-size:10px;fill:var(--muted)}.chart-grid{stroke:var(--border);stroke-dasharray:3 5}.chart-line{fill:none;stroke:var(--accent);stroke-width:2.5;stroke-linecap:round;stroke-linejoin:round}.chart-dot{fill:var(--surface);stroke:var(--accent);stroke-width:2}.chart-bar{fill:var(--accent);opacity:.8}.chart-footer{display:flex;justify-content:space-between;padding:0 22px 15px;color:var(--muted);font-size:10px;gap:15px}.legend{display:flex;gap:8px;align-items:center}.legend:before{content:"";width:17px;height:3px;background:var(--accent);border-radius:2px}.wind-layout{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);align-items:center;gap:35px;padding:14px 30px 24px}.wind-chart{height:260px}.wind-note{padding:20px;background:var(--soft);border-radius:9px}.wind-note h3{font-size:22px;font-weight:550;margin:5px 0}.wind-note p{color:var(--muted);font-size:12px;margin:8px 0}.table-tools{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:17px 22px}.tabs{display:flex;gap:5px;flex-wrap:wrap}.tab{border:0;border-radius:5px;background:transparent;padding:6px 10px;font-size:11px;color:var(--muted);text-transform:capitalize}.tab[aria-pressed=true]{color:var(--accent);background:var(--accent-soft);font-weight:650}.search-wrap{position:relative;min-width:120px}.search-wrap:before{content:"⌕";position:absolute;left:10px;top:4px;color:var(--muted);font-size:20px;pointer-events:none}.search{border:1px solid var(--border);border-radius:6px;background:var(--surface);padding:7px 10px 7px 32px;font-size:11px;width:220px;max-width:100%}.table-scroll{overflow:auto;max-height:420px;overscroll-behavior:contain;border-top:1px solid var(--border);border-bottom:1px solid var(--border)}table{width:100%;border-collapse:separate;border-spacing:0;font-size:12px;font-variant-numeric:tabular-nums;text-align:left}th{background:var(--soft);position:sticky;top:0;z-index:1;font-size:10px;color:var(--muted);font-weight:550;letter-spacing:.2px;border-bottom:1px solid var(--border)}th button{border:0;background:transparent;color:inherit;display:flex;align-items:center;gap:8px;padding:11px 18px;width:100%;text-align:inherit;white-space:nowrap;font-size:inherit}th button:after{content:"↕";opacity:.45}th[aria-sort=ascending] button:after{content:"↑";color:var(--accent);opacity:1}th[aria-sort=descending] button:after{content:"↓";color:var(--accent);opacity:1}td{padding:11px 18px;border-bottom:1px solid var(--border);max-width:360px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}td.numeric,th.numeric{text-align:right}td:first-child{font-weight:550}tbody tr:nth-child(even){background:color-mix(in srgb,var(--soft) 55%,transparent)}tbody tr:hover{background:var(--accent-soft)}tbody tr:last-child td{border-bottom:0}.null{color:var(--muted)}.table-bottom{padding:11px 22px;display:flex;align-items:center;justify-content:space-between;gap:14px;font-size:10px;color:var(--muted)}.pagination{display:flex;align-items:center;gap:10px}.pagination .button{min-height:28px;width:28px;padding:3px;font-size:14px}.empty{padding:34px;text-align:center;color:var(--muted);font-size:12px}.note{color:var(--muted);font-size:11px;padding:12px 16px;background:var(--accent-soft);border-radius:7px;margin:0 0 18px;overflow-wrap:anywhere}.details{font-size:12px}.details summary{cursor:pointer;list-style-position:inside;padding:14px 21px;color:var(--muted)}.details dl{display:grid;grid-template-columns:minmax(140px,1fr) 3fr;gap:10px 20px;margin:0;padding:4px 22px 20px}.details dt{color:var(--muted)}.details dd{margin:0;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.badge{display:inline-flex;align-items:center;gap:6px;font-size:10px;background:var(--accent-soft);color:var(--accent);border-radius:4px;padding:3px 7px}.caption{font-size:11px;color:var(--muted)}footer{display:flex;justify-content:space-between;gap:20px;font-size:10px;color:var(--muted);padding-top:3px}.footer-dot{margin-right:6px;width:5px;height:5px}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}[hidden]{display:none!important} +@media(max-width:740px){#app{padding:0 20px 18px}.topbar{min-height:66px;gap:12px}.edition{display:none}.heading{padding:22px 0 20px}h1{font-size:26px}.hero{gap:15px;padding:23px}.hero-value{font-size:30px}.hero-stat{padding-left:15px}.hero-stat .hero-value{font-size:22px}.metrics{gap:10px;grid-template-columns:repeat(2,minmax(0,1fr))}.metric{padding:15px 16px}.wind-layout{gap:10px;padding:15px}.table-tools{padding:14px}.panel-head{padding:17px 16px 0}.chart-wrap{padding:10px 10px 0}.chart-footer{padding:0 16px 14px}.table-bottom{padding:12px 14px}td{padding:10px 14px}th button{padding:11px 14px}} +@media(max-width:480px){#app{padding:0 14px 16px}.brand{font-size:19px}.connection{font-size:10px}.heading{align-items:flex-start;gap:10px}.eyebrow{font-size:8px;letter-spacing:1.3px}h1{font-size:25px}.subtitle{font-size:10px;max-width:260px}.heading .button{font-size:10px;padding:5px 9px;min-height:32px;margin-top:15px}.hero{grid-template-columns:1fr 1fr;gap:22px 16px;padding:20px}.hero>div:first-child{grid-column:1/-1}.hero-stat{padding-left:0;border-left:0;border-top:1px solid #ffffff22;padding-top:15px}.hero-value{font-size:38px}.hero-stat .hero-value{font-size:24px}.hero-label{font-size:9px}.hero-note{font-size:10px}.metric-value{font-size:25px}.metric-label{font-size:10px}.metrics{gap:9px}.panel-head{flex-wrap:wrap;gap:11px}.panel h2{font-size:14px}.metric-select{max-width:100%;font-size:10px}.chart{height:180px}.chart-wrap{padding:10px 4px 0}.chart-footer{flex-wrap:wrap;gap:5px;font-size:9px}.table-tools{align-items:stretch;flex-direction:column;gap:10px}.search{width:100%}.search-wrap{width:100%}.table-bottom{align-items:flex-start;gap:8px}.pagination{gap:6px;white-space:nowrap}.wind-layout{grid-template-columns:1fr;padding:10px 20px 20px}.wind-chart{height:240px}.details dl{grid-template-columns:1fr 1.5fr;gap:9px 12px;padding:0 16px 17px}.details summary{padding:13px 16px}footer{flex-direction:column;gap:4px;font-size:9px}} +@media(prefers-reduced-motion:no-preference){button{transition:background .12s,border-color .12s}} diff --git a/internal/mcpapp/ui/template.html b/internal/mcpapp/ui/template.html new file mode 100644 index 0000000..b45b10a --- /dev/null +++ b/internal/mcpapp/ui/template.html @@ -0,0 +1,27 @@ + + + + + + + TempestKeep · Weather explorer + + + +
+
+
TempestKeep
+ WEATHER EXPLORER + Connecting +
+
+

YOUR WEATHER, IN CONTEXT

Weather explorer

Waiting for your tool result.

+ +
+
Connecting to your MCP Apps host…
+
+
Powered by your Tempest dataRead-only view · No background polling
+
+ + + diff --git a/internal/version/VERSION b/internal/version/VERSION index 0ea3a94..0d91a54 100644 --- a/internal/version/VERSION +++ b/internal/version/VERSION @@ -1 +1 @@ -0.2.0 +0.3.0 diff --git a/internal/version/version_test.go b/internal/version/version_test.go index 21bb52d..56c87df 100644 --- a/internal/version/version_test.go +++ b/internal/version/version_test.go @@ -6,8 +6,8 @@ func TestStringDevelopmentVersion(t *testing.T) { old := version t.Cleanup(func() { version = old }) version = "" - if got := String(); got != "v0.2.0-dev" { - t.Fatalf("untagged development build = %q, want v0.2.0-dev", got) + if got := String(); got != "v0.3.0-dev" { + t.Fatalf("untagged development build = %q, want v0.3.0-dev", got) } } diff --git a/openspec/changes/add-mcp-apps/.openspec.yaml b/openspec/changes/add-mcp-apps/.openspec.yaml new file mode 100644 index 0000000..a369219 --- /dev/null +++ b/openspec/changes/add-mcp-apps/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-11 diff --git a/openspec/changes/add-mcp-apps/design.md b/openspec/changes/add-mcp-apps/design.md new file mode 100644 index 0000000..5b6772f --- /dev/null +++ b/openspec/changes/add-mcp-apps/design.md @@ -0,0 +1,96 @@ +# Design + +## Context + +The server already exposes typed live-weather and archive tools over stdio. +The existing tool handlers own data access, units, limits, and cancellation. +The frontend renders those results and does not gain direct access to SQLite +or the WeatherFlow API. + +## Decisions + +Use the MCP Apps resource association, `_meta.ui.resourceUri`, on registered +read-only tools when the client advertises the `io.modelcontextprotocol/ui` +extension with `text/html;profile=mcp-app` in its supported MIME types. +Give each association a fixed `ui://tempestkeep/.html` +resource with MIME type `text/html;profile=mcp-app`. Reuse one embedded frontend +bundle with a fixed tool identity for each resource. Serve only known registered +resources. Existing resource discovery for archive schema and dictionary remains. + +Bundle the official `@modelcontextprotocol/ext-apps` SDK with the frontend. +Connect to the host through the SDK before accepting tool notifications. Receive +tool inputs and results, react to host theme changes, and send refresh requests +through that connection. If the host denies tool calls, report the unavailable +action without attempting another transport. + +Refresh only the associated read-only tool using its current arguments. Exclude +archive write tools from app associations and app controls. Disable overlapping +refreshes and retain explicit loading and failure states. Ordinary MCP callers +still receive the original content and structured result. + +Use charts for supported weather series and generic tables or detail views for +other structured results. Search, sort, and page only the received rows. Preserve +numeric sorting, missing values, server truncation, source, and units. Limit +each table display to 2,000 rows and 64 columns and show a notice when this +omits data. An absent measurement must not become zero or a fabricated chart point. Use semantic +controls, visible focus, responsive layouts, and host-compatible light/dark themes. + +Treat labels, SQL cells, API values, and errors as untrusted text. Do not parse +them as HTML. Ship scripts, styles, and visual assets in the same HTML resource. +Declare no external CSP connection or resource origins and request no device +permissions. The host owns iframe sandboxing and permission decisions. + +Commit the generated bundle and the lockfile. Add reproducible build and browser +test commands with Node.js development tooling. Continue to build the production +Go binary directly, including with `CGO_ENABLED=0`, without frontend build tools. + +## Ownership and failure behavior + +The Go server owns its embedded resource bytes and the existing API/database +handles. The host owns the app's sandbox and routes requests to the server. +The app owns only transient display state. Refresh sends no credentials. +No app action creates an archive, collects history, or installs a background job. + +Unknown resources fail through MCP. Missing or malformed results, empty datasets, +failed refreshes, and unavailable host capabilities have visible states. Keep +server query, row, byte, and time limits unchanged. Surface truncation so users +do not mistake a filtered page for the full archive. + +## Compatibility and migration + +Clients that do not advertise the extension retain their ordinary tool metadata +and results. Resources remain discoverable for inspection. +Tool names, schemas, annotations, and structured payloads stay stable. Configured +capabilities still decide which tools and associated UI resources exist. No +archive or configuration migration is required. The terminal UI stays available. + +Propose 0.3.0 as a minor feature version, with no tag or release publication. +Retain this proposal during review even though the baseline MCP specification +also records the full app contract. Archive only after acceptance and completion. +Since the baseline already contains these added requirements, use +`npm run openspec -- archive add-mcp-apps --skip-specs` to avoid applying them +twice. Then run strict validation again. + +## Toolchain qualification + +Pin Go 1.27.2 across the module, repository checks, CI, release qualification, +and current instructions. Keep historical test results tied to their original +run instead of attributing them to the new patch. Run the normal checks and +vulnerability scan with Go 1.27.2 and record the actual result. See +[ADR 0007](../../../docs/adr/0007-go-patch-toolchain.md). +Use golangci-lint v2.14.0 to read the patched compiler's export data while +retaining the existing enabled checks. + +## Validation + +Protocol tests cover discovery and resources over real MCP transports, capability +combinations, unknown URIs, unchanged structured results, and write-tool exclusion. +Browser tests use the SDK bridge, deterministic fixtures, and finite timeouts. +They cover interactive tables, charts, themes, refresh, hostile text, missing +data, failures, and narrow viewports. Screenshot generation uses the same bundle +and synthetic test host, without a live token or personal station data. + +Run `npm run app:build`, `npm run app:test`, `npm run spec:check`, and the +applicable repository Go and documentation checks. Record unavailable checks +as limitations. Actual third-party harness compatibility requires a separate +session in that host and is not implied by synthetic screenshots. diff --git a/openspec/changes/add-mcp-apps/proposal.md b/openspec/changes/add-mcp-apps/proposal.md new file mode 100644 index 0000000..d7ffa5e --- /dev/null +++ b/openspec/changes/add-mcp-apps/proposal.md @@ -0,0 +1,42 @@ +# Add MCP Apps + +## Why + +Weather series and large tables are difficult to explore as chat text alone. +Users need interactive results in their MCP client without opening the separate +terminal dashboard or running another service. + +## What Changes + +- Associate registered read-only tools with embedded MCP Apps HTML resources. +- Show weather charts and searchable, sortable, paginated tables inside supporting hosts. +- Refresh a view through its existing read-only tool and the host's MCP Apps bridge. +- Preserve tool payloads, annotations, capability gating, archive limits, and plain MCP use. +- Document setup, host compatibility, privacy, and reproducible synthetic previews. +- Propose version 0.3.0 and update development and plugin version metadata. +- Pin Go 1.27.2 across builds, verification, CI, and active instructions. + +## Capabilities + +### New Capabilities + +None. MCP Apps extends the existing MCP service. + +### Modified Capabilities + +- `mcp-service`: app discovery, embedded resources, interactive read-only views, + host-mediated refresh, result fidelity, and the browser security boundary. +- `contributor-workflow`: use one Go patch version for builds and qualification. + +## Impact + +MCP tool discovery gains app metadata and resource discovery gains HTML resources. +Original tool schemas and results remain stable. Existing MCP clients can ignore +the extension. Archive storage, configuration, and terminal operation do not change. + +The frontend uses pinned Node.js development dependencies. Its committed bundle +is embedded in Go, so the application needs no Node.js runtime or local web server. +The [ADR](../../../docs/adr/0006-mcp-apps.md) records the protocol and security +decisions. The baseline service specification also includes the new requirements. +The [toolchain ADR](../../../docs/adr/0007-go-patch-toolchain.md) records the +Go 1.27.2 upgrade. Keep this proposal active while the pull request is under review. diff --git a/openspec/changes/add-mcp-apps/specs/contributor-workflow/spec.md b/openspec/changes/add-mcp-apps/specs/contributor-workflow/spec.md new file mode 100644 index 0000000..aba365d --- /dev/null +++ b/openspec/changes/add-mcp-apps/specs/contributor-workflow/spec.md @@ -0,0 +1,23 @@ +## ADDED Requirements + +### Requirement: Consistent Go patch toolchain + +The module, repository verification, CI, release qualification, and active build +instructions MUST use Go 1.27.2. Repository verification MUST reject a different +Go patch version. Historical evidence MUST NOT attribute older test runs to the +newly pinned toolchain. + +#### Scenario: A contributor verifies with the required patch + +- **WHEN** the selected Go toolchain reports go1.27.2 +- **THEN** the version guard permits repository verification to continue + +#### Scenario: A contributor verifies with a different patch + +- **WHEN** the selected Go toolchain reports a version other than go1.27.2 +- **THEN** the version guard fails before running the verification suite + +#### Scenario: A maintainer updates the active toolchain pin + +- **WHEN** a dated test record predates the patch upgrade +- **THEN** the record identifies its results as historical rather than results for the new patch diff --git a/openspec/changes/add-mcp-apps/specs/mcp-service/spec.md b/openspec/changes/add-mcp-apps/specs/mcp-service/spec.md new file mode 100644 index 0000000..a02b80d --- /dev/null +++ b/openspec/changes/add-mcp-apps/specs/mcp-service/spec.md @@ -0,0 +1,106 @@ +## ADDED Requirements + +### Requirement: Read-only MCP Apps discovery + +For clients that advertise the `io.modelcontextprotocol/ui` extension with +`text/html;profile=mcp-app` MIME support, each registered read-only tool MUST +declare `_meta.ui.resourceUri` for its `ui://tempestkeep/.html` resource. The +resource MUST use +MIME type `text/html;profile=mcp-app`. UI resources MUST follow the same +capability rules as their associated tools and remain readable without host UI +support. Write tools MUST NOT declare an app. + +#### Scenario: An archive opens without live access + +- **WHEN** an app-capable client lists tools and resources for an archive-only server +- **THEN** archive read tools have readable UI resources and unavailable live-only tools have none + +#### Scenario: A writable server lists archive collection tools + +- **WHEN** backfill_archive and sync_archive are available +- **THEN** neither tool has an MCP Apps resource association + +#### Scenario: A client requests an unknown app resource + +- **WHEN** resources/read names an unregistered UI URI +- **THEN** the server returns an MCP error instead of arbitrary files or HTML + +### Requirement: Plain MCP compatibility + +MCP Apps MUST preserve tool names, input schemas, structured results, ordinary +content, annotations, and existing capability gates. Clients without app support +MUST remain able to call the same tools and read their results. + +#### Scenario: A client does not support MCP Apps + +- **WHEN** the client calls an available weather or archive tool +- **THEN** it receives the existing ordinary content and structured result without app tool metadata + +### Requirement: Interactive data fidelity + +The app MUST render supported weather series as charts and tabular results as +searchable, sortable, paginated tables. It MUST preserve units, source labels, +server truncation notices, and the distinction between missing readings and zero. +Client-side interactions MUST operate only on received results and MUST NOT +claim to search or page the entire archive. The display MUST limit each table +to 2,000 rows and 64 columns, with a visible notice when it omits data. + +#### Scenario: A table contains numbers, nulls, and a valid zero + +- **WHEN** a user sorts a numeric column +- **THEN** values sort numerically and missing values remain distinct from zero + +#### Scenario: The server truncates a query result + +- **WHEN** a user searches or pages the displayed rows +- **THEN** the view keeps a visible truncation notice and does not imply complete archive coverage + +#### Scenario: A weather measurement is missing + +- **WHEN** the app plots the series +- **THEN** it does not create a zero-valued observation for that missing measurement + +#### Scenario: A SQL result has more than 64 columns + +- **WHEN** the app displays the returned table +- **THEN** it shows at most 64 columns and a display-limit notice without changing the + original tool result + +### Requirement: Host-mediated read-only interaction + +The app MUST use the MCP Apps SDK lifecycle and receive data through the host. +Refresh MUST call only the associated read-only tool with the received arguments. +The app MUST handle host theme changes, loading, empty results, and failed calls. +It MUST NOT invoke archive write tools or access credentials or the archive directly. + +#### Scenario: A user refreshes a history view + +- **WHEN** the host permits app tool calls +- **THEN** the app requests its associated tool through the host with the current arguments + +#### Scenario: The host rejects refresh + +- **WHEN** a refresh request fails or the required capability is unavailable +- **THEN** the view reports failure without a direct API request or archive write + +#### Scenario: The host changes its theme + +- **WHEN** the app receives the updated host context +- **THEN** its display follows that theme without another weather query + +### Requirement: Self-contained untrusted-data display + +The Go binary MUST embed the app HTML, styles, and scripts. Running or building +the Go application MUST NOT require Node.js or a separate frontend service. +The app MUST request no external CSP connection or resource origins and no +device permissions. It MUST render untrusted tool values as text, not executable HTML. + +#### Scenario: A SQL cell contains script-like text + +- **WHEN** the app displays that cell +- **THEN** the text is visible without executing code or making an external request + +#### Scenario: The host reads an app resource offline + +- **WHEN** the server has an existing archive and no live API credentials +- **THEN** the resource contains the assets needed to display its archive results diff --git a/openspec/changes/add-mcp-apps/tasks.md b/openspec/changes/add-mcp-apps/tasks.md new file mode 100644 index 0000000..a48c4a5 --- /dev/null +++ b/openspec/changes/add-mcp-apps/tasks.md @@ -0,0 +1,76 @@ +# Tasks + +## 1. Protocol and resources + +- [x] 1.1 Add read-only app associations and capability-matched resources, then pass MCP + discovery and resource tests. +- [x] 1.2 Preserve original results, annotations, and write-tool boundaries, then pass MCP + compatibility tests. +- [x] 1.3 Embed the self-contained bundle and restrictive resource metadata, then pass + resource and pure-Go build checks. + +## 2. Interactive views + +- [x] 2.1 Add SDK initialization, result handling, refresh, and themes, then pass `npm run + app:test` lifecycle tests. +- [x] 2.2 Add charts and searchable, sortable, paginated tables, then pass `npm run app:test` + interaction tests. +- [x] 2.3 Cover empty, null, error, truncation, hostile-text, and narrow-view cases with `npm + run app:test`. +- [x] 2.4 Rebuild the committed bundle with `npm run app:build` and confirm that no asset + drift remains. + +## 3. Documentation and version + +- [x] 3.1 Update the README, MCP guide, architecture, and threat model, then pass `make docs-check`. +- [x] 3.2 Add the proposed ADR and baseline/change scenarios, then pass `npm run spec:check`. +- [x] 3.3 Propose 0.3.0 consistently in version metadata and release notes, then pass version tests. +- [x] 3.4 Capture Playwright weather and table screenshots with synthetic fixtures and inspect + both images. + +## 4. Review evidence + +- [x] 4.1 Run applicable Go, browser, dependency, and repository checks and record exact + results and limitations. +- [x] 4.2 Review compatibility, security, generated assets, and the complete diff, then + resolve confirmed findings. +- [x] 4.3 Open the pull request with screenshot links, the proposed version, and verification + evidence: [pull request #7](https://github.com/lennrt/tempestkeep/pull/7). + +## 5. Go security patch + +- [x] 5.1 Pin Go 1.27.2 in the module, Makefile, and every Go-based workflow. +- [x] 5.2 Align contributor and release guidance, validate the specifications, and + pass `make verify` with the patched toolchain, including `make vuln`. +- [x] 5.3 Update golangci-lint to v2.14.0 for the patched compiler's export data + and pass the existing lint configuration without disabling checks. + +## Verification evidence + +- On 2026-10-12, full `make verify` passed with Go 1.27.2 and golangci-lint + v2.14.0, including `make vuln` with no vulnerabilities found. All eight + workflow Go pins match the module and Makefile. `make check-go` also rejected + the older locally installed toolchain when automatic selection was disabled. +- `npm run spec:check` passed all six baseline/change items after the toolchain + requirements were added. +- Initial checks with the then-pinned Go toolchain: module verification, + formatting, docs, tidy, vet, standard tests, race tests, all four fuzz targets, + lint, workflow syntax, and public API checks passed. +- `make licenses sbom secrets build-pure build-arm64` passed. +- `make demo-smoke integration e2e docs-check` passed after updating the demo's + discovery count to include the 27 new UI resources. +- `npm run app:check` passed; `npm run app:test` passed all 21 browser checks. +- `npm run app:screenshots` passed. Weather and table images were visually reviewed; + narrow weather, table, and wind views were also inspected at 390 pixels. +- `npm run spec:check` passed all six baseline/change items. +- Initial `make verify` stopped at `make vuln`: nine reachable Go standard-library advisories + in the repository's previous toolchain. A pristine `origin/main` scan produced + byte-identical findings. All nine reported Go 1.27.2 as fixed. The remaining + verification targets were run separately as recorded above. The full patched + run now passes, as recorded at the start of this section. +- `npm audit` reports the existing OpenSpec / fast-glob / micromatch / braces chain + for [GHSA-vfj7-8cjw-p6xm][braces]. No added frontend dependency is flagged. +- Browser checks use the official AppBridge with synthetic data in a sandbox. + They do not certify a specific third-party harness or use real station credentials. + +[braces]: https://github.com/advisories/GHSA-vfj7-8cjw-p6xm diff --git a/openspec/changes/improve-reliability-and-guidance/tasks.md b/openspec/changes/improve-reliability-and-guidance/tasks.md index 428d33f..c19d395 100644 --- a/openspec/changes/improve-reliability-and-guidance/tasks.md +++ b/openspec/changes/improve-reliability-and-guidance/tasks.md @@ -39,7 +39,8 @@ ## Validation record (2026-09-30) -The full Go tests and race suite passed on native Windows with Go 1.27.0. +The full Go tests and race suite passed on native Windows with the then-pinned +Go toolchain. Vet, golangci-lint, formatting, imports, documentation, strict OpenSpec validation, actionlint, module verification, tidy checks, and the public API snapshot passed. Vulnerability and secret scans found no issues. The dependency license check and diff --git a/openspec/config.yaml b/openspec/config.yaml index 1ae7969..c02be6e 100644 --- a/openspec/config.yaml +++ b/openspec/config.yaml @@ -1,7 +1,7 @@ schema: spec-driven context: | - TempestKeep is a Go 1.27 command and MCP stdio server for WeatherFlow Tempest. + TempestKeep is a Go 1.27.2 command and MCP stdio server for WeatherFlow Tempest. Read CONTRIBUTING.md and the relevant docs/adr records before implementation. Store observations in SI units, with exactly one device per SQLite archive. Keep Store reads separate from Writer mutations. Preserve append-only replay. @@ -13,7 +13,9 @@ context: | Add an ADR for public API, wire, storage, security, configuration, or release changes. Use synthetic data and local HTTP servers in tests. Never require a live token. Write short, direct English. Preserve identifiers, units, and technical meaning. - OpenSpec is development tooling; building the Go binary does not require Node.js. + OpenSpec and MCP Apps asset tooling are development-only Node.js dependencies. + Embed the frontend bundle so building or running Go does not require Node.js. + MCP Apps views use existing read-only tools, preserve plain clients, and need no external origins. rules: proposal: diff --git a/openspec/specs/contributor-workflow/spec.md b/openspec/specs/contributor-workflow/spec.md index 557eee8..5089bb0 100644 --- a/openspec/specs/contributor-workflow/spec.md +++ b/openspec/specs/contributor-workflow/spec.md @@ -34,3 +34,25 @@ meaning MUST include an ADR and relevant regression tests. - **WHEN** a contributor changes the meaning of a stored cursor - **THEN** the review includes compatibility guidance and restart regressions + +### Requirement: Consistent Go patch toolchain + +The module, repository verification, CI, release qualification, and active build +instructions MUST use Go 1.27.2. Repository verification MUST reject a different +Go patch version. Historical evidence MUST NOT attribute older test runs to the +newly pinned toolchain. + +#### Scenario: A contributor verifies with the required patch + +- **WHEN** the selected Go toolchain reports go1.27.2 +- **THEN** the version guard permits repository verification to continue + +#### Scenario: A contributor verifies with a different patch + +- **WHEN** the selected Go toolchain reports a version other than go1.27.2 +- **THEN** the version guard fails before running the verification suite + +#### Scenario: A maintainer updates the active toolchain pin + +- **WHEN** a dated test record predates the patch upgrade +- **THEN** the record identifies its results as historical rather than results for the new patch diff --git a/openspec/specs/mcp-service/spec.md b/openspec/specs/mcp-service/spec.md index 45e9bd7..e668c88 100644 --- a/openspec/specs/mcp-service/spec.md +++ b/openspec/specs/mcp-service/spec.md @@ -45,3 +45,108 @@ boundary and MUST reject a start that is not before that boundary. - **WHEN** the date inputs describe an empty backfill range - **THEN** the tool rejects the range without collecting observations + +### Requirement: Read-only MCP Apps discovery + +For clients that advertise the `io.modelcontextprotocol/ui` extension with +`text/html;profile=mcp-app` MIME support, each registered read-only tool MUST +declare `_meta.ui.resourceUri` for its `ui://tempestkeep/.html` resource. The +resource MUST use +MIME type `text/html;profile=mcp-app`. UI resources MUST follow the same +capability rules as their associated tools and remain readable without host UI +support. Write tools MUST NOT declare an app. + +#### Scenario: An archive opens without live access + +- **WHEN** an app-capable client lists tools and resources for an archive-only server +- **THEN** archive read tools have readable UI resources and unavailable live-only tools have none + +#### Scenario: A writable server lists archive collection tools + +- **WHEN** backfill_archive and sync_archive are available +- **THEN** neither tool has an MCP Apps resource association + +#### Scenario: A client requests an unknown app resource + +- **WHEN** resources/read names an unregistered UI URI +- **THEN** the server returns an MCP error instead of arbitrary files or HTML + +### Requirement: Plain MCP compatibility + +MCP Apps MUST preserve tool names, input schemas, structured results, ordinary +content, annotations, and existing capability gates. Clients without app support +MUST remain able to call the same tools and read their results. + +#### Scenario: A client does not support MCP Apps + +- **WHEN** the client calls an available weather or archive tool +- **THEN** it receives the existing ordinary content and structured result without app tool metadata + +### Requirement: Interactive data fidelity + +The app MUST render supported weather series as charts and tabular results as +searchable, sortable, paginated tables. It MUST preserve units, source labels, +server truncation notices, and the distinction between missing readings and zero. +Client-side interactions MUST operate only on received results and MUST NOT +claim to search or page the entire archive. The display MUST limit each table +to 2,000 rows and 64 columns, with a visible notice when it omits data. + +#### Scenario: A table contains numbers, nulls, and a valid zero + +- **WHEN** a user sorts a numeric column +- **THEN** values sort numerically and missing values remain distinct from zero + +#### Scenario: The server truncates a query result + +- **WHEN** a user searches or pages the displayed rows +- **THEN** the view keeps a visible truncation notice and does not imply complete archive coverage + +#### Scenario: A weather measurement is missing + +- **WHEN** the app plots the series +- **THEN** it does not create a zero-valued observation for that missing measurement + +#### Scenario: A SQL result has more than 64 columns + +- **WHEN** the app displays the returned table +- **THEN** it shows at most 64 columns and a display-limit notice without changing the + original tool result + +### Requirement: Host-mediated read-only interaction + +The app MUST use the MCP Apps SDK lifecycle and receive data through the host. +Refresh MUST call only the associated read-only tool with the received arguments. +The app MUST handle host theme changes, loading, empty results, and failed calls. +It MUST NOT invoke archive write tools or access credentials or the archive directly. + +#### Scenario: A user refreshes a history view + +- **WHEN** the host permits app tool calls +- **THEN** the app requests its associated tool through the host with the current arguments + +#### Scenario: The host rejects refresh + +- **WHEN** a refresh request fails or the required capability is unavailable +- **THEN** the view reports failure without a direct API request or archive write + +#### Scenario: The host changes its theme + +- **WHEN** the app receives the updated host context +- **THEN** its display follows that theme without another weather query + +### Requirement: Self-contained untrusted-data display + +The Go binary MUST embed the app HTML, styles, and scripts. Running or building +the Go application MUST NOT require Node.js or a separate frontend service. +The app MUST request no external CSP connection or resource origins and no +device permissions. It MUST render untrusted tool values as text, not executable HTML. + +#### Scenario: A SQL cell contains script-like text + +- **WHEN** the app displays that cell +- **THEN** the text is visible without executing code or making an external request + +#### Scenario: The host reads an app resource offline + +- **WHEN** the server has an existing archive and no live API credentials +- **THEN** the resource contains the assets needed to display its archive results diff --git a/package-lock.json b/package-lock.json index bd4787e..f3d9cb4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,12 +7,457 @@ "name": "tempestkeep-development-tools", "license": "MIT", "devDependencies": { - "@fission-ai/openspec": "1.13.2" + "@fission-ai/openspec": "1.13.2", + "@modelcontextprotocol/ext-apps": "2.0.3", + "@playwright/test": "1.64.0", + "esbuild": "0.28.2" }, "engines": { "node": ">=20.19.0" } }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@fission-ai/openspec": { "version": "1.13.2", "resolved": "https://registry.npmjs.org/@fission-ai/openspec/-/openspec-1.13.2.tgz", @@ -382,6 +827,75 @@ } } }, + "node_modules/@modelcontextprotocol/client": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.3.1.tgz", + "integrity": "sha512-mIGZXpHsjnZ6lD+gD/WCMpR5k8yVQQ8nNFH1N0Srf7AvnwTUMYD6pvTY8ng2+He5FfV7YMZLmrjL7cLa/cc3dQ==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "@modelcontextprotocol/core": "2.3.1", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.8", + "jose": "^6.1.3", + "pkce-challenge": "^5.0.0", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.3.1.tgz", + "integrity": "sha512-laVmIhPGpWi7rG9q+0UigblRN0Hws/Yjlb6qLFtVqryXVLkc4h+yN8z731POD2LnAGQlFe7/tXhUm7Bi0YB91g==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/ext-apps": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/ext-apps/-/ext-apps-2.0.3.tgz", + "integrity": "sha512-Tn+4+cyhO4f4cQSDxNyLiIfEE+qlTTuIbWBJB8JTinEXOhDYgCT4wDTQplxD9MBYZH5pCYGC59GaxiwIT4bu8w==", + "dev": true, + "license": "MIT", + "workspaces": [ + "examples/*" + ], + "dependencies": { + "@standard-schema/spec": "^1.1.0" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@modelcontextprotocol/client": "^2.0.0", + "@modelcontextprotocol/core": "^2.0.0", + "@modelcontextprotocol/server": "^2.0.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0", + "zod": "^4.2.0" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/server": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -420,6 +934,29 @@ "node": ">= 8" } }, + "node_modules/@playwright/test": { + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.0.tgz", + "integrity": "sha512-oTN9FNYuN6bqQMwiho6jJKLCG2/QOYCixGXuCjRmzOq23eODeukuY2XiAVoVpAECbuezMt1MHQjAiQxK8F+Y+g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.64.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, "node_modules/ansi-regex": { "version": "6.4.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz", @@ -540,6 +1077,73 @@ "node": ">=0.3.1" } }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/fast-glob": { "version": "3.3.3", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", @@ -716,6 +1320,17 @@ "dev": true, "license": "ISC" }, + "node_modules/jose": { + "version": "6.2.12", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz", + "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==", + "dev": true, + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/log-symbols": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-7.0.1.tgz", @@ -842,6 +1457,46 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/playwright": { + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.0.tgz", + "integrity": "sha512-kVzTnYFYEyQ9RGzBjNCd2+yEqWmVbxl3AHPynv3qQ6JTjv4a+kwRcnqQwIpuP3NnrnIrE/Q6wWAIAvMfIE2/Yg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.64.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.0.tgz", + "integrity": "sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", diff --git a/package.json b/package.json index 079f746..7bdac69 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "tempestkeep-development-tools", "private": true, - "description": "Development-only specification checks for the TempestKeep Go project", + "description": "Development-only specifications and MCP Apps assets for the TempestKeep Go project", "license": "MIT", "engines": { "node": ">=20.19.0" @@ -9,9 +9,16 @@ "scripts": { "spec:check": "openspec validate --all --strict --no-interactive", "spec:list": "openspec list --specs", - "openspec": "openspec" + "openspec": "openspec", + "app:build": "node scripts/build-mcp-app.mjs", + "app:check": "node scripts/build-mcp-app.mjs --check", + "app:test": "playwright test", + "app:screenshots": "node scripts/capture-mcp-app.mjs" }, "devDependencies": { - "@fission-ai/openspec": "1.13.2" + "@fission-ai/openspec": "1.13.2", + "@modelcontextprotocol/ext-apps": "2.0.3", + "@playwright/test": "1.64.0", + "esbuild": "0.28.2" } } diff --git a/pkg/tempest/collect/collect.go b/pkg/tempest/collect/collect.go index 93f69f6..2157bd4 100644 --- a/pkg/tempest/collect/collect.go +++ b/pkg/tempest/collect/collect.go @@ -153,7 +153,8 @@ func nilInterface(value any) bool { return true } reflected := reflect.ValueOf(value) - switch reflected.Kind() { //nolint:exhaustive // Only kinds that can be nil need explicit handling. + //nolint:exhaustive // Only kinds that can be nil need explicit handling. + switch reflected.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: return reflected.IsNil() default: diff --git a/playwright.config.mjs b/playwright.config.mjs new file mode 100644 index 0000000..e0bb9d0 --- /dev/null +++ b/playwright.config.mjs @@ -0,0 +1,15 @@ +import { defineConfig } from '@playwright/test'; + +export default defineConfig({ + testDir: './tests/mcp-app', + outputDir: './dist/playwright', + timeout: 30_000, + expect: { timeout: 8_000 }, + fullyParallel: true, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 1 : 0, + workers: 2, + reporter: 'list', + use: { baseURL: 'http://127.0.0.1:4177', browserName: 'chromium', viewport: { width: 1280, height: 1000 }, locale: 'en-US', timezoneId: 'America/Los_Angeles', trace: 'retain-on-failure' }, + webServer: { command: 'node tests/mcp-app/serve.mjs', url: 'http://127.0.0.1:4177', reuseExistingServer: false, timeout: 30_000 }, +}); diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 4d24013..cfdb720 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,8 +1,8 @@ { "name": "tempestkeep", "displayName": "TempestKeep", - "version": "0.2.0", - "description": "MCP integration for live and archived Tempest data.", + "version": "0.3.0", + "description": "MCP tools and interactive MCP Apps for live and archived Tempest data.", "author": { "name": "Lennart Rudolph", "url": "https://github.com/lennrt/tempestkeep" diff --git a/plugin/README.md b/plugin/README.md index 307a6dd..6be1baf 100644 --- a/plugin/README.md +++ b/plugin/README.md @@ -4,9 +4,13 @@ This package connects `tempestkeep mcp` to Claude Code. It contains three commands and one station-analysis skill. Other MCP clients can use the server directly without this plugin. +MCP Apps views are part of the server. A host must support the MCP Apps extension +to render them. Loading this plugin alone does not establish that support. See +the [MCP Apps guide](../docs/mcp-apps.md). + ## Prepare the server -Build `tempestkeep` from the repository root with Go 1.27.0: +Build `tempestkeep` from the repository root with Go 1.27.2: ```sh make tempestkeep diff --git a/scripts/build-mcp-app.mjs b/scripts/build-mcp-app.mjs new file mode 100644 index 0000000..53cbd27 --- /dev/null +++ b/scripts/build-mcp-app.mjs @@ -0,0 +1,51 @@ +import { build } from "esbuild"; +import { readFile, readdir, writeFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const directory = `${root}internal/mcpapp/ui/`; +const version = (await readFile(`${root}internal/version/VERSION`, "utf8")).trim(); +const result = await build({ + absWorkingDir: root, + entryPoints: ["internal/mcpapp/ui/app.js"], + bundle: true, + minify: true, + format: "iife", + platform: "browser", + target: ["es2022"], + legalComments: "inline", + metafile: true, + define: { __TEMPESTKEEP_VERSION__: JSON.stringify(version) }, + write: false, +}); +const template = await readFile(`${directory}template.html`, "utf8"); +const css = await readFile(`${directory}style.css`, "utf8"); +// Escape HTML script terminators even when they occur inside bundled strings. +const javascript = result.outputFiles[0].text.replace(/<\/script/gi, "<\\/script"); +// Carry the licenses of every bundled dependency into the Go binary. esbuild's +// legalComments covers source headers, but packages also ship license files. +const packages = [...new Set(Object.keys(result.metafile.inputs).map(path => path.match(/^node_modules\/((?:@[^/]+\/)?[^/]+)/)?.[1]).filter(Boolean))].sort(); +const notices = []; +for (const name of packages) { + const packageRoot = `${root}node_modules/${name}/`; + const metadata = JSON.parse(await readFile(`${packageRoot}package.json`, "utf8")); + const files = (await readdir(packageRoot)).filter(name => /^(licen[cs]e|notice)(\.|$)/i.test(name)).sort(); + if (!files.length) throw new Error(`Bundled package ${name} has no license file.`); + for (const filename of files) { + const license = (await readFile(`${packageRoot}${filename}`, "utf8")).replace(/[ \t]+$/gm, ""); + notices.push(`${name}@${metadata.version} — ${filename}\n\n${license}`); + } +} +const licenses = `/g, "-->")}\n-->\n`; +// Function replacements keep JavaScript's $&, $` and $' sequences literal. +const html = template.replace("/* APP_STYLES */", () => css).replace("/* APP_SCRIPT */", () => javascript).replace("", () => `${licenses}`); +const destination = `${directory}app.html`; +if (process.argv.includes("--check")) { + if (await readFile(destination, "utf8") !== html) { + throw new Error("MCP App bundle is stale. Run npm run app:build and commit app.html."); + } + console.log("MCP App bundle matches its sources."); +} else { + await writeFile(destination, html); + console.log(`Built MCP App (${Math.round(Buffer.byteLength(html) / 1024)} KiB).`); +} diff --git a/scripts/capture-mcp-app.mjs b/scripts/capture-mcp-app.mjs new file mode 100644 index 0000000..a87fca9 --- /dev/null +++ b/scripts/capture-mcp-app.mjs @@ -0,0 +1,7 @@ +import { spawnSync } from 'node:child_process'; + +const result = spawnSync(process.execPath, ['node_modules/@playwright/test/cli.js', 'test', '--grep', 'documentation screenshots'], { + stdio: 'inherit', env: { ...process.env, CAPTURE_SCREENSHOTS: '1' }, +}); +if (result.error) throw result.error; +process.exit(result.status ?? 1); diff --git a/scripts/check-mcp-demo.sh b/scripts/check-mcp-demo.sh index 8496709..7265be4 100755 --- a/scripts/check-mcp-demo.sh +++ b/scripts/check-mcp-demo.sh @@ -11,7 +11,7 @@ NO_COLOR=1 TEMPEST_TOKEN=synthetic-unused-token TEMPEST_READ_ONLY=true \ "$repo_root/scripts/demo-agent.sh" -pace 0 -hold 0 >"$transcript" for expected in \ - '29 tools / 2 resources / 3 prompts discovered' \ + '29 tools / 29 resources / 3 prompts discovered' \ '0 observations stored' \ 'has_more=true' \ 'reached the start of history' \ diff --git a/tests/mcp-app/app.spec.mjs b/tests/mcp-app/app.spec.mjs new file mode 100644 index 0000000..7652096 --- /dev/null +++ b/tests/mcp-app/app.spec.mjs @@ -0,0 +1,211 @@ +import { test, expect } from '@playwright/test'; +import { mkdir } from 'node:fs/promises'; +import { observations, query } from './fixtures.mjs'; + +async function openApp(page, view = 'weather', extra = '') { + await page.goto(`/?view=${view}${extra}`); + await expect.poll(() => page.evaluate(() => window.fixtureHost?.initialized)).toBe(true); + const app = page.frameLocator('iframe'); + if (!extra.includes('loading')) await expect(app.locator('#content')).toHaveAttribute('aria-busy', 'false'); + return app; +} + +test('official host bridge renders weather, changes metrics, and refreshes the original arguments', async ({ page }) => { + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + const requests = []; + page.on('request', (request) => requests.push(request.url())); + const app = await openApp(page); + await expect(app.locator('h1')).toContainText(/observations|weather|archive/i); + await expect(app.locator('svg').first()).toBeVisible(); + await expect(app.locator('table tbody tr').first()).toBeVisible(); + const select = app.locator('.metric-select').first(); + const before = await app.locator('.chart').first().textContent(); + await select.selectOption({ index: 1 }); + await expect(app.locator('.chart').first()).not.toHaveText(before); + await app.getByRole('button', { name: 'Refresh', exact: false }).click(); + await expect.poll(() => page.evaluate(() => window.fixtureHost.calls.length)).toBe(1); + expect(await page.evaluate(() => window.fixtureHost.calls[0])).toMatchObject({ + name: 'get_observations', arguments: { start: '2026-06-14', end: '2026-06-14', bucket_minutes: 30 }, + }); + expect(requests.every((url) => url.startsWith('http://127.0.0.1:4177/'))).toBe(true); + expect(errors).toEqual([]); +}); + +test('SQL table filters, sorts numerically, paginates, and shows truncation', async ({ page }) => { + const app = await openApp(page, 'table'); + await expect(app.locator('table tbody tr')).toHaveCount(8); + await expect(app.locator('#content')).toContainText(/more rows|truncat|limit/i); + const next = app.getByRole('button', { name: /next page/i }); + await next.click(); + await expect(app.locator('table tbody tr').first()).toContainText('2026-04-09'); + await app.locator('input[type="search"]').fill('Partial'); + await expect(app.locator('table tbody tr')).toHaveCount(1); + await expect(app.locator('table tbody tr').first()).toContainText('2026-04-06'); + await app.locator('input[type="search"]').fill(''); + await app.locator('thead th').nth(1).getByRole('button').click(); + await expect(app.locator('thead th').nth(1)).toHaveAttribute('aria-sort', 'ascending'); + const values = await app.locator('tbody tr td:nth-child(2)').allTextContents(); + const nums = values.map((value) => Number(value.replaceAll(',', ''))).filter(Number.isFinite); + expect(nums).toEqual([...nums].sort((a, b) => a - b)); + await app.locator('thead th').nth(1).getByRole('button').click(); + await expect(app.locator('thead th').nth(1)).toHaveAttribute('aria-sort', 'descending'); + await app.locator('input[type="search"]').fill('does not exist'); + await expect(app.locator('#content')).toContainText(/no .*match|no results/i); +}); + +test('missing values remain distinct from zero and hostile cells remain text', async ({ page }) => { + const app = await openApp(page, 'table'); + await page.evaluate(async () => window.fixtureHost.send({ + columns: ['label', 'reading'], rows: [['', null], ['measured zero', 0]], row_count: 2, + })); + await expect(app.locator('tbody tr')).toHaveCount(2); + await expect(app.locator('tbody tr').first()).toContainText(' window.injected)).toBeUndefined(); +}); + +test('query column order and duplicate labels retain every value', async ({ page }) => { + const app = await openApp(page, 'table'); + await page.evaluate(() => window.fixtureHost.send({ columns: ['value', 'value', '__proto__'], rows: [[12, 34, 'safe']], row_count: 1 })); + await expect(app.locator('tbody tr td')).toHaveText(['12', '34', 'safe']); +}); + +test('a missing temperature produces a gap instead of a zero reading', async ({ page }) => { + const app = await openApp(page); + const sparse = structuredClone(observations); + sparse.points = [sparse.points[0], { ...sparse.points[1], temp_avg_f: null }, sparse.points[2]]; + await page.evaluate((data) => window.fixtureHost.send(data), sparse); + await expect(app.locator('tbody tr')).toHaveCount(3); + await expect(app.locator('tbody tr').nth(1)).toContainText('—'); + await expect(app.locator('.chart-line')).toHaveCount(2); +}); + +test('absent archive buckets break the plotted line', async ({ page }) => { + const app = await openApp(page); + const sparse = { ...observations, points: [observations.points[0], observations.points[1], observations.points[5], observations.points[6]] }; + await page.evaluate((data) => window.fixtureHost.send(data), sparse); + await expect(app.locator('.chart-line')).toHaveCount(2); +}); + +test('an empty wind rose does not invent a preferred direction', async ({ page }) => { + const app = await openApp(page, 'wind'); + await page.evaluate(() => { + const data = structuredClone(window.fixtureHost.fixture.data); + data.obs = 0; data.calm_pct = 0; + data.sectors.forEach((row) => { row.pct = 0; row.count = 0; }); + return window.fixtureHost.send(data); + }); + await expect(app.locator('.wind-note')).toContainText('No directional readings'); +}); + +for (const view of ['daily', 'forecast', 'wind', 'conditions']) { + test(`${view} tool view renders its actual structured shape`, async ({ page }) => { + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + const app = await openApp(page, view); + await expect(app.locator('.hero')).toBeVisible(); + if (view !== 'conditions') await expect(app.locator('svg').first()).toBeVisible(); + if (view === 'conditions') await expect(app.locator('#content')).toContainText(/archive/i); + expect(errors).toEqual([]); + }); +} + +test('host theme updates and narrow screens keep the document in bounds', async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + const app = await openApp(page, 'table', '&theme=dark'); + await expect(app.locator('html')).toHaveAttribute('data-theme', 'dark'); + await page.evaluate(() => window.fixtureHost.setTheme('light')); + await expect(app.locator('html')).toHaveAttribute('data-theme', 'light'); + expect(await page.frames()[1].evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true); + await expect(app.getByRole('button', { name: /next page/i })).toBeVisible(); +}); + +test('empty results and a failed refresh recover without losing the result', async ({ page }) => { + const app = await openApp(page, 'table'); + await page.evaluate(() => { window.fixtureHost.nextError = 'Synthetic refresh failed'; }); + await app.getByRole('button', { name: /refresh/i }).click(); + await expect(app.locator('#message')).toContainText(/failed|error|could not/i); + await expect(app.locator('tbody tr')).toHaveCount(8); + await app.getByRole('button', { name: /refresh/i }).click(); + await expect(app.locator('#message')).toBeHidden(); + await page.evaluate(() => window.fixtureHost.send({ columns: ['day', 'rain_mm'], rows: [], row_count: 0 })); + await expect(app.locator('#content')).toContainText(/no .*rows|no .*data|no .*results|no readings/i); +}); + +test('loading state performs no automatic tool calls', async ({ page }) => { + const app = await openApp(page, 'weather', '&loading'); + await expect(app.locator('#message')).toBeVisible(); + expect(await page.evaluate(() => window.fixtureHost.calls)).toEqual([]); + await page.evaluate((data) => window.fixtureHost.send(data), observations); + await expect(app.locator('svg').first()).toBeVisible(); +}); + +test('a host without tool capability cannot trigger refresh', async ({ page }) => { + const app = await openApp(page, 'weather', '&noTools'); + await expect(app.locator('#refresh')).toBeDisabled(); + expect(await page.evaluate(() => window.fixtureHost.calls)).toEqual([]); +}); + +test('refresh waits for the original input instead of inventing arguments', async ({ page }) => { + const app = await openApp(page, 'table', '&noInput'); + await expect(app.locator('#refresh')).toBeDisabled(); + expect(await page.evaluate(() => window.fixtureHost.calls)).toEqual([]); +}); + +test('plain JSON text content is a supported result fallback', async ({ page }) => { + const app = await openApp(page, 'table'); + await page.evaluate((data) => window.fixtureHost.bridge.sendToolResult({ content: [{ type: 'text', text: JSON.stringify(data) }] }), { ...query, rows: query.rows.slice(0, 2), row_count: 2, truncated: false }); + await expect(app.locator('tbody tr')).toHaveCount(2); +}); + +test('large results are bounded before rendering and disclose the display limit', async ({ page }) => { + const app = await openApp(page, 'table'); + await page.evaluate(() => window.fixtureHost.send({ + columns: Array.from({ length: 70 }, (_, i) => `column_${i}`), + rows: Array.from({ length: 2100 }, (_, i) => Array.from({ length: 70 }, (_, j) => i + j)), + row_count: 2100, + })); + await expect(app.locator('thead th')).toHaveCount(64); + await expect(app.locator('tbody tr')).toHaveCount(8); + await expect(app.locator('#content')).toContainText('Display limited to 2,000 rows and 64 columns'); +}); + +test('a late refresh cannot replace a newer host-pushed result', async ({ page }) => { + const app = await openApp(page, 'table'); + await page.evaluate(() => { window.fixtureHost.holdNextCall = true; }); + await app.locator('#refresh').click(); + await expect.poll(() => page.evaluate(() => typeof window.fixtureHost.releaseCall)).toBe('function'); + await expect(app.locator('#refresh')).toBeDisabled(); + await page.evaluate(async () => { + await window.fixtureHost.send({ columns: ['newer'], rows: [['Latest host result']], row_count: 1 }); + window.fixtureHost.releaseCall(); + // A round-trip ensures queued bridge messages are delivered before assertions. + await window.fixtureHost.bridge.request({ method: 'ping' }); + }); + await expect(app.locator('tbody tr')).toHaveCount(1); + await expect(app.locator('tbody')).toContainText('Latest host result'); +}); + +test('malformed results surface an error and recover on valid host data', async ({ page }) => { + const app = await openApp(page, 'table'); + await page.evaluate(() => window.fixtureHost.bridge.sendToolResult({ content: [{ type: 'text', text: '{invalid JSON' }] })); + await expect(app.locator('#message')).toContainText('invalid JSON'); + await expect(app.locator('table')).toHaveCount(0); + await page.evaluate((data) => window.fixtureHost.send(data), query); + await expect(app.locator('tbody tr')).toHaveCount(8); +}); + +test('documentation screenshots', async ({ page }) => { + await page.setViewportSize({ width: 1280, height: 1100 }); + for (const [view, name] of [['weather', 'mcp-app-weather.png'], ['table', 'mcp-app-table.png']]) { + const app = await openApp(page, view); + await expect(app.locator('tbody tr').first()).toBeVisible(); + if (process.env.CAPTURE_SCREENSHOTS === '1') { + await mkdir('docs/screenshots', { recursive: true }); + await page.locator('iframe').screenshot({ path: `docs/screenshots/${name}`, animations: 'disabled' }); + } + } +}); diff --git a/tests/mcp-app/fixtures.mjs b/tests/mcp-app/fixtures.mjs new file mode 100644 index 0000000..8d9d6fb --- /dev/null +++ b/tests/mcp-app/fixtures.mjs @@ -0,0 +1,77 @@ +// Deliberately synthetic observations. Never substitute a private archive here. +const day = (index) => `2026-06-${String(index + 1).padStart(2, '0')}`; +const rounded = (n) => Math.round(n * 100) / 100; + +export const observations = { + from: '2026-06-14T00:00:00-07:00', + to: '2026-06-14T23:59:59-07:00', + bucket_minutes: 30, + points: Array.from({ length: 48 }, (_, i) => { + const hour = String(Math.floor(i / 2)).padStart(2, '0'); + const time = `2026-06-14T${hour}:${i % 2 ? '30' : '00'}:00-07:00`; + const temp = 64 + 11 * Math.sin((i - 13) * Math.PI / 30) + Math.sin(i * 1.7) * 0.7; + return { + epoch: Date.parse(time) / 1000, time, + temp_avg_f: rounded(temp), temp_min_f: rounded(temp - 0.8), temp_max_f: rounded(temp + 1.2), + humidity_pct: rounded(64 - (temp - 60) * 1.4), pressure_inhg: rounded(30.12 - i * 0.002), + wind_mph: rounded(3 + Math.max(0, Math.sin((i - 15) / 10)) * 6), + gust_mph: rounded(6 + Math.max(0, Math.sin((i - 15) / 10)) * 9), + rain_in: i >= 39 && i <= 42 ? 0.02 : 0, + uv_max: rounded(Math.max(0, Math.sin((i - 12) * Math.PI / 26)) * (i < 40 ? 7 : 0)), + solar_avg_wm2: rounded(Math.max(0, Math.sin((i - 12) * Math.PI / 26)) * (i < 40 ? 780 : 0)), + lightning_strikes: 0, obs: 30, + }; + }), +}; + +export const daily = { + from: day(0), to: day(13), + days: Array.from({ length: 14 }, (_, i) => ({ + day: day(i), temp_min_f: rounded(51 + Math.sin(i) * 4), + temp_max_f: rounded(73 + Math.sin(i / 3) * 8), temp_avg_f: rounded(63 + Math.sin(i / 3) * 5), + rain_in: i % 5 === 1 ? 0.23 : 0, peak_gust_mph: rounded(8 + Math.abs(Math.sin(i) * 13)), obs: 1440, + })), +}; + +export const query = { + columns: ['day', 'temperature_c', 'humidity_pct', 'rain_mm', 'peak_wind_mps', 'observations', 'coverage'], + rows: Array.from({ length: 64 }, (_, i) => [ + new Date(Date.UTC(2026, 3, i + 1)).toISOString().slice(0, 10), + i === 5 ? null : rounded(17 + Math.sin(i / 5) * 6), + rounded(60 + Math.cos(i / 4) * 14), i % 7 === 2 ? 4.8 : 0, + rounded(3 + Math.abs(Math.sin(i)) * 7), i === 5 ? 960 : 1440, + i === 5 ? 'Partial' : 'Complete', + ]), + row_count: 64, + truncated: true, + note: 'Synthetic daily aggregates. SQL values keep their selected units; more rows exist beyond this result.', +}; + +export const forecast = { + station: 'Demo garden · synthetic station', + current: { time: observations.points[30].time, conditions: 'Partly cloudy', temp_f: 72.4, feels_like_f: 71.8, humidity_pct: 52 }, + daily: daily.days.slice(0, 7).map((d, i) => ({ date: d.day, conditions: i === 2 ? 'Light rain' : 'Partly cloudy', high_f: d.temp_max_f, low_f: d.temp_min_f, precip_probability: i === 2 ? 65 : 10, sunrise: '05:42', sunset: '20:31' })), + hourly: observations.points.filter((_, i) => i % 2 === 0).map((p) => ({ time: p.time, conditions: 'Partly cloudy', temp_f: p.temp_avg_f, feels_like_f: p.temp_avg_f, precip_probability: 10, wind_mph: p.wind_mph, gust_mph: p.gust_mph, wind_dir: 'SW' })), +}; + +const sectors = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']; +export const wind = { + from: day(0), to: day(13), calm_pct: 12.5, calm_threshold_mph: 1.118, obs: 16000, + sectors: sectors.map((sector, i) => ({ sector, count: i < 8 ? 200 : 1550, pct: (i < 8 ? 200 : 1550) / 140, avg_mph: rounded(4 + Math.sin(i) * 2), max_gust_mph: rounded(11 + Math.sin(i) * 4) })), +}; + +export const fixtures = { + weather: { tool: 'get_observations', args: { start: day(13), end: day(13), bucket_minutes: 30 }, data: observations }, + table: { tool: 'query_sql', args: { + sql: "SELECT date(epoch, 'unixepoch') AS day, AVG(air_temp_c) AS temperature_c, AVG(humidity) AS humidity_pct, SUM(rain_mm) AS rain_mm, MAX(wind_gust) AS peak_wind_mps, COUNT(*) AS observations, CASE WHEN COUNT(*) >= 1440 THEN 'Complete' ELSE 'Partial' END AS coverage FROM obs_st GROUP BY day ORDER BY day", + max_rows: 64, + }, data: query }, + daily: { tool: 'daily_summary', args: { start: day(0), end: day(13) }, data: daily }, + forecast: { tool: 'forecast', args: { hours: 24, days: 7 }, data: forecast }, + wind: { tool: 'wind_rose', args: { start: day(0), end: day(13) }, data: wind }, + conditions: { tool: 'current_conditions', args: {}, data: { source: 'archive', time: observations.points[30].time, age_seconds: 900, temp_f: 72.4, humidity_pct: 0, rain_today_in: 0, wind_mph: 4.6, gust_mph: 8.2, note: 'Synthetic archive fallback.' } }, +}; + +export function toolResult(data) { + return { content: [{ type: 'text', text: JSON.stringify(data) }], structuredContent: data, isError: false }; +} diff --git a/tests/mcp-app/host.js b/tests/mcp-app/host.js new file mode 100644 index 0000000..1e1f23c --- /dev/null +++ b/tests/mcp-app/host.js @@ -0,0 +1,40 @@ +import { AppBridge, PostMessageTransport } from '@modelcontextprotocol/ext-apps/app-bridge'; + +const params = new URLSearchParams(location.search); +const fixture = await fetch(`/fixture?view=${encodeURIComponent(params.get('view') || 'weather')}`).then((r) => r.json()); +const frame = document.querySelector('iframe'); +const theme = params.get('theme') === 'dark' ? 'dark' : 'light'; +const bridge = new AppBridge(null, { name: 'TempestKeep synthetic test host', version: '1.0.0' }, + params.has('noTools') ? {} : { serverTools: {} }, + { hostContext: { theme, displayMode: 'inline', availableDisplayModes: ['inline'], platform: 'web' } }); +const host = window.fixtureHost = { + bridge, fixture, calls: [], initialized: false, nextError: null, + holdNextCall: false, releaseCall: null, + async send(data) { await bridge.sendToolResult({ content: [{ type: 'text', text: JSON.stringify(data) }], structuredContent: data }); }, + async error(message) { await bridge.sendToolResult({ content: [{ type: 'text', text: message }], isError: true }); }, + setTheme(value) { bridge.setHostContext({ theme: value }); }, +}; +bridge.oncalltool = async (request) => { + host.calls.push(request); + if (request.name !== fixture.tool) throw new Error('Test host allows only the mounted read tool'); + if (host.holdNextCall) { + host.holdNextCall = false; + await new Promise((resolve) => { host.releaseCall = resolve; }); + } + if (host.nextError) { + const message = host.nextError; + host.nextError = null; + return { content: [{ type: 'text', text: message }], isError: true }; + } + return { content: [{ type: 'text', text: JSON.stringify(fixture.data) }], structuredContent: fixture.data }; +}; +bridge.onsizechange = ({ height }) => { + if (height > 0) frame.style.height = `${Math.min(6000, Math.ceil(height))}px`; +}; +bridge.oninitialized = async () => { + host.initialized = true; + if (!params.has('noInput')) await bridge.sendToolInput({ arguments: fixture.args }); + if (!params.has('loading')) await host.send(fixture.data); +}; +await bridge.connect(new PostMessageTransport(frame.contentWindow, frame.contentWindow)); +frame.src = `/app?tool=${encodeURIComponent(fixture.tool)}`; diff --git a/tests/mcp-app/serve.mjs b/tests/mcp-app/serve.mjs new file mode 100644 index 0000000..ade51d4 --- /dev/null +++ b/tests/mcp-app/serve.mjs @@ -0,0 +1,33 @@ +import { createServer } from 'node:http'; +import { readFile } from 'node:fs/promises'; +import { build } from 'esbuild'; +import { fixtures } from './fixtures.mjs'; + +const root = new URL('../../', import.meta.url); +const bundle = await build({ entryPoints: [new URL('./host.js', import.meta.url).pathname], bundle: true, write: false, format: 'esm', platform: 'browser', target: 'es2022', logLevel: 'warning' }); +const app = await readFile(new URL('internal/mcpapp/ui/app.html', root), 'utf8'); +const html = `TempestKeep · synthetic MCP Apps preview
TempestKeep / MCP AppsSynthetic data · local test host
`; +const csp = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; connect-src 'none'; font-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'"; +const server = createServer((req, res) => { + const url = new URL(req.url, 'http://127.0.0.1'); + res.setHeader('Cache-Control', 'no-store'); + if (url.pathname === '/') { + res.setHeader('Content-Type', 'text/html; charset=utf-8'); + res.end(html); + } else if (url.pathname === '/host.js') { + res.setHeader('Content-Type', 'text/javascript; charset=utf-8'); + res.end(bundle.outputFiles[0].contents); + } else if (url.pathname === '/fixture' && fixtures[url.searchParams.get('view')]) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(fixtures[url.searchParams.get('view')])); + } else if (url.pathname === '/app' && Object.values(fixtures).some((f) => f.tool === url.searchParams.get('tool'))) { + res.setHeader('Content-Type', 'text/html; charset=utf-8'); + res.setHeader('Content-Security-Policy', csp); + res.end(app.replaceAll('__TEMPESTKEEP_TOOL__', url.searchParams.get('tool'))); + } else { + res.statusCode = 404; + res.end('Not found'); + } +}); +server.listen(4177, '127.0.0.1', () => console.log('Synthetic MCP Apps host: http://127.0.0.1:4177')); +for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => server.close(() => process.exit(0)));