diff --git a/.github/workflows/validation-ci.yml b/.github/workflows/validation-ci.yml index 9e3c45aa4..0c0e32382 100644 --- a/.github/workflows/validation-ci.yml +++ b/.github/workflows/validation-ci.yml @@ -31,6 +31,8 @@ on: - "examples/tpcds_semantic_model.yaml" - ".github/workflows/validation-ci.yml" - "scripts/generate-spec-types.py" + - "scripts/generate-mcp-profile.py" + - "docs/proposals/execute-query-mcp.md" pull_request: branches: ["main"] paths: @@ -42,6 +44,8 @@ on: - "examples/tpcds_semantic_model.yaml" - ".github/workflows/validation-ci.yml" - "scripts/generate-spec-types.py" + - "scripts/generate-mcp-profile.py" + - "docs/proposals/execute-query-mcp.md" permissions: contents: read @@ -80,6 +84,9 @@ jobs: - name: Check spec.yaml enums are in sync with ossie-schema.json run: uv run scripts/generate-spec-types.py --check + - name: Check MCP profile schemas and examples are in sync + run: uv run scripts/generate-mcp-profile.py --check + - name: Validate canonical example run: uv run validation/validate.py examples/tpcds_semantic_model.yaml diff --git a/docs/index.md b/docs/index.md index fa71bb83c..471de01b0 100644 --- a/docs/index.md +++ b/docs/index.md @@ -63,6 +63,13 @@ The specification supports multiple SQL dialects (`ANSI_SQL`, `SNOWFLAKE`, `DATA For the full specification, see [core-spec/spec.md](../core-spec/spec.md). For validation tooling, see [validation/validate.py](../validation/validate.py). For a complete example, see the [TPC-DS semantic model](../examples/tpcds_semantic_model.yaml). +### Execution Contract Proposal + +The [execute_query MCP working draft](proposals/execute-query-mcp.md) proposes an +optional engine/catalog execution profile: model-resolved Layer 3 query objects, +embedded CSV, semantic diagnostics, locale-neutral encoding and MCP Tasks. +It is not an adopted specification or an Ossie server implementation. + ### Participating Organizations Ossie is supported by a broad coalition of 50+ organizations across the data ecosystem, including: diff --git a/docs/proposals/execute-query-mcp.md b/docs/proposals/execute-query-mcp.md new file mode 100644 index 000000000..eac05cef3 --- /dev/null +++ b/docs/proposals/execute-query-mcp.md @@ -0,0 +1,682 @@ + + +# Proposal: `execute_query` MCP profile + +**Status:** Proposed, `0.4-draft`. An optional execution contract for engines and +catalogs, not an Ossie server implementation or a condition of model conformance. +MUST, SHOULD and MAY describe requirements of this proposed profile. + +## Scope + +Execute an agent-authored, read-only **Layer 3 query object resolved against an +Ossie model**; return embedded data, optional previews and actionable diagnostics. +The engine owns model resolution, safe planning and authorization; the calling +agent owns analytical intent and correction. Native SQL/DAX/KQL execution, +Layer 2 queries, query generation, writes, batches, federation, model +authoring/conversion and client-input round trips are outside this profile. +Adoption does not change the core model schema, converters, or API/CLI access. + +This complements model management/discovery rather than prescribing it: +[MCP discussion #510](https://github.com/apache/ossie/discussions/510), +[execution-contract proposal on dev@](https://lists.apache.org/thread/olc629g9zmqgx66bo2hdl9hg0on6jtlg), +[specification versus implementation](https://lists.apache.org/thread/wpj5nnpodysds1vqd2s1vxhzw0vkcndy), +and the [REST proposal](https://lists.apache.org/thread/hf71m6g1g1bnhqj5v0f4kc0rf4h8g4kg). +Query semantics are those of the [Layer 3 Foundation draft][layer3], pinned to +`cc0d0709` from [#246](https://github.com/apache/ossie/pull/246). This profile +defines its JSON/MCP binding, not new join, grain or filter semantics. +The dependency remains proposed, not an adopted standard. Layer 2's relational +interface ([#354](https://github.com/apache/ossie/pull/354)) is separate. +The [declarative-scope discussion](https://lists.apache.org/thread/9007r91vf33y04grtk8yn58nqc4oyco) +motivates model-resolved input and direct semantic error codes. + +## Binding and request + +A catalog, REST API, MCP resource/tool or deployment configuration MUST expose +the source's opaque `data_source_id`, bound **model identity and revision**, +profile and Foundation revisions, supported query shapes/capabilities, output +formats, diagnostic capabilities and execution/materialization ceilings. +Each call MUST resolve against one fixed authorized model revision; successful +results identify it. No mandatory discovery endpoint or core model connection +property is introduced. +The server MUST resolve and authorize the binding for the caller; model names +and dataset sources are not credentials or globally unique execution IDs. +An execution binding ID MUST NOT be reassigned to a different model or revision; +updating the model publishes a new binding, and retired IDs return +`SOURCE_UNAVAILABLE`. This prevents an agent's discovered model from being +silently replaced between discovery and execution. + +Tool name: `execute_query`. `inputSchema`: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "additionalProperties": false, + "required": ["data_source_id", "query"], + "properties": { + "data_source_id": { "type": "string", "minLength": 1, "pattern": "\\S" }, + "query": { "$ref": "#/$defs/query" } + }, + "$defs": { + "expression": { "type": "string", "minLength": 1, "pattern": "\\S" }, + "projection": { "type": "array", "items": { "$ref": "#/$defs/expression" } }, + "predicate": { + "oneOf": [ + { "$ref": "#/$defs/expression" }, + { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/expression" } } + ] + }, + "query": { + "type": "object", "additionalProperties": false, + "properties": { + "dimensions": { "$ref": "#/$defs/projection" }, + "measures": { "$ref": "#/$defs/projection" }, + "fields": { "allOf": [{ "$ref": "#/$defs/projection" }], "minItems": 1 }, + "where": { "$ref": "#/$defs/predicate" }, + "having": { "$ref": "#/$defs/predicate" }, + "order_by": { + "type": "array", "minItems": 1, + "items": { + "type": "object", "additionalProperties": false, "required": ["field"], + "properties": { + "field": { "$ref": "#/$defs/expression" }, + "direction": { "enum": ["ASC", "DESC"] }, + "nulls": { "enum": ["FIRST", "LAST"] } + } + } + }, + "limit": { "type": "integer", "minimum": 0 } + }, + "oneOf": [ + { + "not": { "required": ["fields"] }, + "anyOf": [ + { "required": ["dimensions"], "properties": { "dimensions": { "minItems": 1 } } }, + { "required": ["measures"], "properties": { "measures": { "minItems": 1 } } } + ] + }, + { + "required": ["fields"], + "not": { "anyOf": [{ "required": ["dimensions"] }, { "required": ["measures"] }, { "required": ["having"] }] } + } + ] + } + } +} +``` + +### Layer 3 surface and interpretation + +This schema serializes Foundation section 5, not a native query inside JSON. +Property names are lowercase; `query` contains the clauses directly, +without another `query` wrapper. All expression strings use the portable +`OSSIE_SQL_2026` expression language and resolve only against the bound model. +Statement text, native dialects, connection properties, query parameters, joins, +grain overrides and undeclared clauses are outside the surface. + +| Clause / shape | Contract | +| --- | --- | +| Aggregation | `dimensions` and/or `measures`, at least one nonempty. Omitted arrays mean empty. No `fields`; empty dimensions request totals. | +| Scalar | Nonempty `fields`; no `dimensions`, `measures` or `having`, even if empty. Foundation table-grain and fan-out rules apply. | +| Projections | Dimensions/fields/metrics, ad-hoc expressions and aliases follow Foundation section 5 and its expression subset. Schema validity alone does not establish name, type, grain or expression validity. | +| `where` / `having` | One predicate string or a nonempty list interpreted as AND. Row-level versus aggregate/window predicates follow Foundation sections 6.3/6.10; OR is inside an expression. | +| `order_by` | Objects containing `field` (in-scope name or projection-valid expression), optional `direction` (default `ASC`) and `nulls`. `nulls: FIRST/LAST` explicitly serializes section 5's NULL placement; defaults are ASC/LAST, DESC/FIRST. Positional ordinals are not allowed. | +| `limit` | Nonnegative integer bounding final query rows, including zero; absent means no query-authored cap. Accepted without ordering, but no stable row selection is implied. Server ceilings are independent and any resulting truncation is disclosed. | + +The engine resolves names, relationships, join paths and grain-safe aggregation +according to the pinned Foundation, not backend-native semantics. Implementation +may compile to SQL/DAX or another engine representation internally; that does +not change the accepted interface or its meaning. Model expressions without a +supported semantics-preserving evaluation MUST be refused, not interpreted as +native text or silently dropped. + +Bindings MUST advertise supported shapes and capability restrictions (such as +M:N traversal, windows, multi-fact queries or path length). Partial implementations +MUST refuse unsupported cases explicitly; exposing this MCP profile does not +claim full Foundation conformance. Reuse an applicable Foundation refusal code +where defined; otherwise return `UNSUPPORTED_QUERY` with the missing capability. +Unsettled Foundation semantics are resolved there, not by inventing backend +defaults here; implementations unable to guarantee the declared semantics MUST +refuse the case. Shape-only tests do not establish equivalent answers. + +Each call returns one table. Semantics-preserving compilation is expected; +semantic query mutation, automatic repair/retry, broadened filters, source +fallback and discarded result tables are prohibited. No `language`, connection, +impersonation, external limits or diagnostic arguments are accepted. +Suggested annotations are `readOnlyHint: true`, +`destructiveHint: false` and an `openWorldHint` reflecting the actual deployment; +annotations are not enforcement or an idempotence guarantee. + +## Results + +A final `CallToolResult` MUST contain concise Markdown-readable status, +completeness, attachment names and applicable guidance. Successful calls, +including zero rows, use `isError: false`; tool failures use `isError: true`. +Malformed MCP envelopes, unknown tools and protocol-capability failures use +protocol errors instead. No failure may masquerade as successful empty data. + +Structured output is RECOMMENDED. A tool advertising `outputSchema` MUST supply +conforming `structuredContent` on success and tool errors; Markdown-only +compatibility MAY omit both. `outputSchema` constrains that object, not content +blocks or Task handles. Text, structured fields and embedded resources MUST +agree. MCP's recommended serialized-JSON text fallback SHOULD be provided +where needed, without duplicating the full dataset in prose. +Every successful result MUST identify the evaluated model and revision; +Markdown-only results carry that identity in text or resource metadata. + +### Data and previews + +Success MUST include CSV as an embedded MCP resource: `type: "resource"` with +`resource.uri`, `mimeType: "text/csv"` and `text`. Known-schema zero-row results +produce header-only CSV; missing column schema is an explicit unsupported-result +error. Optional XLSX/Parquet use separate base64 `resource.blob` blocks with +`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` or +`application/vnd.apache.parquet`. All formats represent the same materialized +rows, columns and values, without re-execution. + +Use safe, distinct filename-like URI labels (`file:///sales.csv`), not private +paths or credentials. Embedded bytes are already in the response; the URI +implies neither a physical file nor `resources/read`. Hosts determine how to +save/expose attachments. Resource links do not replace embedded CSV in this +profile. If delivery exceeds policy, return `RESOURCE_LIMIT` with narrowing +guidance, not preview-only success. Base64 overhead counts toward ceilings; +Tasks solve latency, not payload size. Servers embedding resources SHOULD +implement the resources capability, without promising retrieval of every label. + +Preview selection is non-normative guidance; no row count or first-row rule is +required: + +| Selection | Recommended use | +| --- | --- | +| First few rows, often 5-10 | Economical default; without ordering these are not ranked "top" rows. | +| All rows | Small results within a cell/byte budget. | +| Labeled sample | Exploration; no implied order or statistical representativeness. | +| No preview | Wide/large values; retain column metadata and embedded data. | + +An optional structured preview MUST preserve exact cells, positional column +arity and JSON nulls; it MUST NOT synthesize statistics as query rows. Shortened +Markdown cells MUST be labeled and retain originals in CSV. Display selection +does not change execution. `preview.row_count` equals displayed rows; +`result.row_count` equals materialized rows excluding the header; +`preview.has_more` equals `result.row_count > preview.row_count`. +Independently, `result.completeness` is `complete` only with evidence of query +exhaustion, `truncated` with evidence of omitted rows, otherwise `unknown`. +Query-authored `limit` is query semantics, not export truncation. Capped or +sampled materializations MUST NOT be described as complete. + +### Diagnostics + +Every final result includes diagnostic availability, suggestions and filter +alternatives; empty arrays are valid. Applicable enrichment SHOULD be produced +under server policy, not an input flag. Supplemental probes MUST share caller +authorization, RLS/OLS and aggregate budgets. Partial/unavailable enrichment +requires an explanation, not an implied exhaustive search or a changed primary +query outcome. Zero rows remain success. + +Suggestions are advice: `replacement_query` is a complete **Layer 3 object +matching the same query schema**, not native text, a JSON-encoded string or a +patch. It remains scoped to the same source/model and is never automatically +executed. Static examples are not verified query results. +Alternatives identify candidates for the original authorized filter field; +cross-field hints belong in suggestions. Their `complete` flag concerns +candidate search, not query completeness. Unauthorized names/values, connection +strings, credentials and stack traces MUST NOT appear in diagnostics. + +The structured core is extensible through namespaced object-valued `extensions`; +clients MUST tolerate unfamiliar extension keys, error codes and guidance kinds, +but extensions cannot override core status, access or execution semantics. +Common codes: `INVALID_ARGUMENT`, `SOURCE_UNAVAILABLE`, `UNSUPPORTED_QUERY`, +`QUERY_REJECTED`, `QUERY_INVALID`, `PERMISSION_DENIED`, `TIMEOUT`, `CANCELLED`, +`RESOURCE_LIMIT`, `BACKEND_ERROR`. `SOURCE_UNAVAILABLE` may conceal inaccessible +bindings; error source IDs echo supplied values, not privileged resolved IDs. +Guidance kinds include `name`, `query`, `filter`, `limit`, `diagnostic`. + +Foundation semantic refusals MUST appear unchanged in **`error.code`**, not +only in `extensions` or flattened to `QUERY_INVALID`. For example, +`E_NAME_NOT_FOUND`, `E_NO_PATH`, `E_AMBIGUOUS_PATH` and +`E3013_NO_STITCHING_DIMENSION` retain their defined triggers. +Mixed/empty query shapes use `E_MIXED_QUERY_SHAPE`, +`E_EMPTY_AGGREGATION_QUERY` or `E_EMPTY_SCALAR_QUERY` when applicable. +Expression parsing failures without a Foundation code use `QUERY_INVALID`; +malformed clause values use `INVALID_ARGUMENT`; valid but unsupported evaluation +uses `UNSUPPORTED_QUERY` unless Foundation defines a capability code. +Do not assign a semantic-invalid code merely because an engine lacks a planner +feature. Provider diagnostics MAY extend the error without overriding its code. + +## Encoding and presentation + +| Concern | Requirement / guidance | +| --- | --- | +| CSV syntax | UTF-8, header, comma delimiter, RFC 4180 quoting of commas/quotes/newlines. Preserve column positions and duplicate names. | +| Null versus string | Null is unquoted `\N`; non-null strings beginning with `\` gain one leading `\` before CSV quoting. Decode null first, then remove the escape prefix. Empty strings remain empty; literal `\N` becomes `\\N`. Headers are not null/escape encoded. | +| Independent interpretation | Every CSV resource MUST carry `_meta["org.apache.ossie/execute_query"]` with ordered column descriptors, row count, completeness, `csv_null_value` and `csv_escape_prefix`. Structured descriptors/preview MUST agree; this is profile metadata, not an MCP-defined key. | +| Logical types | Reuse core types; omit unknown types. Integer/Decimal use exact decimal strings; Float uses finite JSON numbers/invariant CSV text; Boolean uses JSON booleans/CSV `true` or `false`. Opaque values require a declared encoding. Never repair unknown arity/types by dropping cells. | +| Locale | Machine values MUST be locale-neutral: `.` decimals, no grouping/currency/percent suffixes, invariant signs/exponents and preserved scale. `0.125` is not changed to display `12.5%`. | +| Date/time | ISO 8601 with precision preserved. Distinguish civil `DateTime` from offset-bearing `DateTimeTz`; do not invent a timezone. Offsets identify instants, not necessarily named zones. Available zone/unit/currency/collation detail belongs in namespaced metadata. | +| Strings and UI | Preserve identifiers, Unicode, case, whitespace and leading zeros. UI prose MAY be localized independently; disclose display rounding. Readers SHOULD disable automatic locale/type guessing. | +| Spreadsheet safety | Do not silently prefix formulas or alter analytical CSV values. Warn about spreadsheet interpretation; optional XLSX should use appropriately typed, safe cells. | + +### Token economy + +Hosts SHOULD expose full attachments to file/data tooling rather than inject +CSV/base64 into model context; audience annotations are hints, not isolation or +confidentiality. LLM-facing output SHOULD contain one short outcome, optional +economical preview and actionable guidance, avoiding repeated query/schema/data +or error text. Candidate lists may be bounded if incompleteness is disclosed; +exact structured values MUST NOT be replaced by ellipses. Future additions +SHOULD justify decision value and token cost across tiny, wide, large, empty and +error results; additional formats are optional, not mandatory duplication. + +## Structured output schema + +The following schema applies only to final `structuredContent`. Requirements +outside JSON Schema include preview/resource consistency and encoding rules above. + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "additionalProperties": false, + "required": ["contract_version", "status", "diagnostics", "suggestions", "filter_value_alternatives"], + "properties": { + "contract_version": { "const": "0.4-draft" }, + "status": { "enum": ["success", "error"] }, + "data_source_id": { "type": "string", "minLength": 1 }, + "model": { + "type": "object", "additionalProperties": false, "required": ["id", "revision"], + "properties": { + "id": { "type": "string", "minLength": 1 }, + "revision": { "type": "string", "minLength": 1 } + } + }, + "preview": { + "type": "object", "additionalProperties": false, + "required": ["columns", "rows", "row_count", "has_more"], + "properties": { + "columns": { + "type": "array", "minItems": 1, + "items": { + "type": "object", "additionalProperties": false, "required": ["name"], + "properties": { + "name": { "type": "string" }, + "datatype": { "enum": ["String", "Integer", "Decimal", "Float", "Boolean", "Date", "Time", "DateTime", "DateTimeTz", "Opaque"] } + } + } + }, + "rows": { "type": "array", "items": { "type": "array", "items": {} } }, + "row_count": { "type": "integer", "minimum": 0 }, + "has_more": { "type": "boolean" }, + "selection": { "enum": ["first_rows", "sample"] } + } + }, + "result": { + "type": "object", "additionalProperties": false, + "required": ["row_count", "completeness", "resources"], + "properties": { + "row_count": { "type": "integer", "minimum": 0 }, + "completeness": { "enum": ["complete", "truncated", "unknown"] }, + "resources": { + "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/resource" }, + "contains": { "type": "object", "required": ["format"], "properties": { "format": { "const": "csv" } } } + }, + "extensions": { "$ref": "#/$defs/extensions" } + } + }, + "error": { + "type": "object", "additionalProperties": false, "required": ["code", "message", "retryable"], + "properties": { + "code": { "type": "string", "minLength": 1 }, + "message": { "type": "string", "minLength": 1 }, + "retryable": { "type": "boolean" }, + "extensions": { "$ref": "#/$defs/extensions" } + } + }, + "diagnostics": { + "type": "object", "additionalProperties": false, "required": ["state"], + "properties": { + "state": { "enum": ["completed", "partial", "unavailable", "not_applicable"] }, + "message": { "type": "string", "minLength": 1 }, + "extensions": { "$ref": "#/$defs/extensions" } + }, + "if": { "properties": { "state": { "enum": ["partial", "unavailable"] } } }, + "then": { "required": ["message"] } + }, + "suggestions": { + "type": "array", + "items": { + "type": "object", "additionalProperties": false, "required": ["kind", "message"], + "properties": { + "kind": { "type": "string", "minLength": 1 }, + "message": { "type": "string", "minLength": 1 }, + "replacement_query": { "$ref": "#/$defs/query" }, + "extensions": { "$ref": "#/$defs/extensions" } + } + } + }, + "filter_value_alternatives": { + "type": "array", + "items": { + "type": "object", "additionalProperties": false, + "required": ["field", "requested_value", "values", "match", "complete"], + "properties": { + "field": { "type": "string", "minLength": 1 }, + "requested_value": {}, + "values": { "type": "array", "items": {} }, + "match": { "enum": ["exact", "fuzzy", "unknown"] }, + "complete": { "type": "boolean" }, + "extensions": { "$ref": "#/$defs/extensions" } + } + } + }, + "extensions": { "$ref": "#/$defs/extensions" } + }, + "$defs": { + "expression": { "type": "string", "minLength": 1, "pattern": "\\S" }, + "projection": { "type": "array", "items": { "$ref": "#/$defs/expression" } }, + "predicate": { + "oneOf": [ + { "$ref": "#/$defs/expression" }, + { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/expression" } } + ] + }, + "query": { + "type": "object", "additionalProperties": false, + "properties": { + "dimensions": { "$ref": "#/$defs/projection" }, + "measures": { "$ref": "#/$defs/projection" }, + "fields": { "allOf": [{ "$ref": "#/$defs/projection" }], "minItems": 1 }, + "where": { "$ref": "#/$defs/predicate" }, + "having": { "$ref": "#/$defs/predicate" }, + "order_by": { + "type": "array", "minItems": 1, + "items": { + "type": "object", "additionalProperties": false, "required": ["field"], + "properties": { + "field": { "$ref": "#/$defs/expression" }, + "direction": { "enum": ["ASC", "DESC"] }, + "nulls": { "enum": ["FIRST", "LAST"] } + } + } + }, + "limit": { "type": "integer", "minimum": 0 } + }, + "oneOf": [ + { + "not": { "required": ["fields"] }, + "anyOf": [ + { "required": ["dimensions"], "properties": { "dimensions": { "minItems": 1 } } }, + { "required": ["measures"], "properties": { "measures": { "minItems": 1 } } } + ] + }, + { + "required": ["fields"], + "not": { "anyOf": [{ "required": ["dimensions"] }, { "required": ["measures"] }, { "required": ["having"] }] } + } + ] + }, + "extensions": { "type": "object", "additionalProperties": { "type": "object" } }, + "resource": { + "type": "object", "additionalProperties": false, + "required": ["uri", "name", "format", "mime_type"], + "properties": { + "uri": { "type": "string", "format": "uri" }, + "name": { "type": "string", "minLength": 1 }, + "format": { "type": "string", "minLength": 1 }, + "mime_type": { "type": "string", "minLength": 1 }, + "csv_null_value": { "const": "\\N" }, + "csv_escape_prefix": { "const": "\\" }, + "extensions": { "$ref": "#/$defs/extensions" } + }, + "if": { "properties": { "format": { "const": "csv" } } }, + "then": { + "required": ["csv_null_value", "csv_escape_prefix"], + "properties": { "mime_type": { "const": "text/csv" } } + } + } + }, + "oneOf": [ + { "properties": { "status": { "const": "success" } }, "required": ["data_source_id", "model", "result"], "not": { "required": ["error"] } }, + { "properties": { "status": { "const": "error" } }, "required": ["error"], "not": { "anyOf": [{ "required": ["preview"] }, { "required": ["result"] }] } } + ] +} +``` + +## MCP execution and safety + +This profile uses [MCP 2026-07-28 tools][mcp-tools] and [resources][mcp-resources], +with the optional [Tasks extension][mcp-tasks]. Implementations MUST follow the +selected MCP version; the application schema does not replace protocol schemas. + +| Mechanism | Profile application | +| --- | --- | +| Discovery | Modern `server/discover` and authorized `tools/list` advertise only implemented capabilities. Source bindings remain catalog data, not connection state. Supported cacheable discover/list/read RPCs include `ttlMs`/`cacheScope`; private metadata is authorization-isolated. List cursors do not paginate CSV/query rows. | +| Request envelope | Per-request protocol version/client capabilities belong in `params._meta`. HTTP uses matching `MCP-Protocol-Version`, `Mcp-Method` and `Mcp-Name` (`execute_query` for calls, Task ID for Task RPCs), never query text in headers. | +| Progress/cancellation | Synchronous `_meta.progressToken` may report throttled phases without invented percentages. HTTP response-stream closure or stdio `notifications/cancelled` signals request cancellation; propagate backend cleanup where possible. | +| Durable Tasks | Servers SHOULD support long-running query/materialization through negotiated `io.modelcontextprotocol/tasks`. Create a durable flat `resultType: "task"` handle only for a declaring client; poll `tasks/get`, cancel with `tasks/cancel`. Completed Task `result` is the final `CallToolResult`, including tool errors; `failed` is for JSON-RPC faults. | +| Notifications/recovery | Optional Task subscriptions supplement polling, not repeated execution. Task cancellation is cooperative. Initial response loss gives no exactly-once guarantee; once a Task ID is known, resume polling it. Cache freshness, retention TTL and runtime deadlines are independent. | +| Compatibility | 2025-11-25 deployments use their own initialization, experimental task capability/request fields and `tasks/result`; do not mix them into the modern protocol. Latest/draft core schemas were identical at the pinned review commit. | + +Server policy MUST bound request validation, planning, execution, +materialization and probes; Tasks do not relax ceilings. Authorize model +elements, sources, resources and Tasks for the effective caller, preserving +RLS/OLS. Parse/resolve expression fragments before safe compilation; do not +concatenate unchecked text into native statements. Enforce +read-only through engine permissions/compiler controls, not annotation or +string-prefix tests. Protected remote endpoints follow MCP authorization; +upstream credentials have separate audiences, with no arbitrary token +passthrough. Prefer bounded self-contained schemas/local `$defs`, not automatic +network `$ref` fetching. Optional trace context is envelope metadata, not source +authority; `_meta` is not confidential. Data and guidance are untrusted content. + +The profile introduces no client-input round trips, model sampling, filesystem +Roots, query-authoring prompts or Apps/Skills dependency. Deprecated +Roots/Sampling/Logging are not adopted. Optional server onboarding/UI features +are separate concerns, not execution requirements. + +## Examples + +Aggregation query against the bound model: + +```json +{ + "data_source_id": "sales-model", + "query": { + "dimensions": ["customers.region"], + "measures": ["total_revenue"], + "where": "orders.status = 'completed'", + "order_by": [{ "field": "total_revenue", "direction": "DESC", "nulls": "LAST" }], + "limit": 20 + } +} +``` + +Scalar query; predicate lists are AND-conjoined and omitted ordering options +use the profile defaults: + +```json +{ + "data_source_id": "sales-model", + "query": { + "fields": ["orders.order_id", "orders.amount", "customers.region"], + "where": ["orders.status = 'completed'", "orders.amount > 0"], + "order_by": [{ "field": "orders.order_id" }], + "limit": 100 + } +} +``` + +Modern request; Task support is declared, not demanded: + +```json +{ + "jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": { + "name": "execute_query", + "arguments": { + "data_source_id": "sales-model", + "query": { + "dimensions": ["customers.region"], + "measures": ["total_revenue"], + "where": "orders.status = 'completed'", + "order_by": [{ "field": "total_revenue", "direction": "DESC", "nulls": "LAST" }], + "limit": 20 + } + }, + "_meta": { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": { + "extensions": { "io.modelcontextprotocol/tasks": {} } + } + } + } +} +``` + +Successful `CallToolResult` body; preview and CSV metadata correlate: + +```json +{ + "resultType": "complete", "isError": false, + "content": [ + { "type": "text", "text": "1 row; complete. Data: sales.csv. No applicable filter guidance." }, + { + "type": "resource", + "resource": { + "uri": "file:///sales.csv", "mimeType": "text/csv", + "text": "region,total_revenue\r\nWest,12345.67\r\n", + "_meta": { + "org.apache.ossie/execute_query": { + "columns": [ + { "name": "region", "datatype": "String" }, + { "name": "total_revenue", "datatype": "Decimal" } + ], + "row_count": 1, "completeness": "complete", + "csv_null_value": "\\N", "csv_escape_prefix": "\\" + } + } + }, + "annotations": { "audience": ["user", "assistant"] } + } + ], + "structuredContent": { + "contract_version": "0.4-draft", "status": "success", + "data_source_id": "sales-model", + "model": { "id": "sales", "revision": "r1" }, + "preview": { + "columns": [ + { "name": "region", "datatype": "String" }, + { "name": "total_revenue", "datatype": "Decimal" } + ], + "rows": [["West", "12345.67"]], "row_count": 1, "has_more": false + }, + "result": { + "row_count": 1, "completeness": "complete", + "resources": [{ + "uri": "file:///sales.csv", "name": "sales.csv", + "format": "csv", "mime_type": "text/csv", + "csv_null_value": "\\N", "csv_escape_prefix": "\\" + }] + }, + "diagnostics": { "state": "not_applicable" }, + "suggestions": [], "filter_value_alternatives": [] + } +} +``` + +Tool error with extensible, advisory repair guidance: + +```json +{ + "resultType": "complete", "isError": true, + "content": [{ + "type": "text", + "text": "Unknown metric `total_reveneu`; use `total_revenue`. No replacement query executed." + }], + "structuredContent": { + "contract_version": "0.4-draft", "status": "error", + "data_source_id": "sales-model", + "model": { "id": "sales", "revision": "r1" }, + "error": { + "code": "E_NAME_NOT_FOUND", + "message": "Unknown metric 'total_reveneu'; did you mean 'total_revenue'?", + "retryable": false, + "extensions": { "example.org/parser": { "line": 1 } } + }, + "diagnostics": { "state": "completed" }, + "suggestions": [{ + "kind": "query", "message": "Use the known total_revenue metric.", + "replacement_query": { + "dimensions": ["customers.region"], + "measures": ["total_revenue"], + "where": "orders.status = 'completed'", + "order_by": [{ "field": "total_revenue", "direction": "DESC", "nulls": "LAST" }], + "limit": 20 + } + }], + "filter_value_alternatives": [] + } +} +``` + +Deferred result body, only with negotiated Task support: + +```json +{ + "resultType": "task", "taskId": "query-task-example", "status": "working", + "createdAt": "2026-10-06T13:30:00Z", "lastUpdatedAt": "2026-10-06T13:30:00Z", + "ttlMs": 3600000, "pollIntervalMs": 1000 +} +``` + +`tasks/get` returns `resultType: "complete"` with Task state; on `completed`, +its nested `result` is the same final tool result. A Task handle is not a CSV URI +and is not validated by the application `outputSchema`. + +## Conformance + +Adapters MUST resolve the bound model and Layer 3 semantics and preserve typed +pre-formatting results, nulls/precision, completeness and embedded bytes rather +than reverse-parse lossy +previews or claim conformance by tool name. Relevant cases include aggregation, +scalar, mixed/empty shapes; name/path/grain/filter validation; valid but +unsupported capabilities; two-fact queries and Having; zero rows; +absent/first-row/sample previews; row-arity and +duplicate-name fidelity; CSV escapes, locale and exact numerics; partial +materialization/enrichment; resource budgets; permission refusals; extensible +tool errors; cancellation/reconnect; and Task tool-error versus protocol-fault +states. No reference engine or adapter implementation is included. `0.4-draft` +replaces native strings/language selection with Layer 3 objects and uses the +same object for repairs; it is not wire-compatible with `0.3-draft`. + +### Implementor contract checks + +[Reusable schemas and an offline checker](../../validation/mcp/README.md) +validate endpoint implementors' tool declarations and captured final results: +arguments/repair objects, status/source/model consistency, embedded CSV, +encoding metadata and preview fidelity. The published schemas are generated +from this profile; no semantic planner or endpoint is introduced. +Reports distinguish passed, failed and unverified captures and list unchecked +obligations. Passing captured contract tests does not certify authorization, +read-only execution, Foundation query answers or the MCP transport/Task lifecycle. + +[layer3]: https://github.com/apache/ossie/blob/cc0d07099a3ef31e85af1fd93458a52186fae2c6/core-spec/foundational_semantics.md +[mcp-tools]: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/0a11bf68c7ec4473526ec15589f592afcd12d1e8/docs/specification/2026-07-28/server/tools.mdx +[mcp-resources]: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/0a11bf68c7ec4473526ec15589f592afcd12d1e8/docs/specification/2026-07-28/server/resources.mdx +[mcp-tasks]: https://github.com/modelcontextprotocol/ext-tasks/blob/93a4915aadf714f87ece5cd40c317bce24779cf5/specification/2026-07-28/tasks.md diff --git a/scripts/generate-mcp-profile.py b/scripts/generate-mcp-profile.py new file mode 100644 index 000000000..49d8cca80 --- /dev/null +++ b/scripts/generate-mcp-profile.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Publish executable schemas and an endpoint capture from the profile examples.""" + +import argparse +import json +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +PROFILE = ROOT / "docs/proposals/execute-query-mcp.md" +DESTINATION = ROOT / "validation/mcp" +LICENSE = ( + "Licensed to the Apache Software Foundation (ASF) under one or more " + "contributor license agreements. See NOTICE for copyright ownership. " + "Licensed under the Apache License, Version 2.0; " + "http://www.apache.org/licenses/LICENSE-2.0 . " + "Unless required by applicable law or agreed to in writing, distributed " + "on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND." +) + + +def generated_files() -> dict[str, str]: + blocks = [ + json.loads(block) + for block in re.findall(r"```json\n(.*?)\n```", PROFILE.read_text(encoding="utf-8"), re.S) + ] + schemas = [block for block in blocks if "$schema" in block] + if len(schemas) != 2: + raise ValueError("Expected exactly the input and output schemas in the profile") + inputs, outputs = schemas + for name in ("expression", "projection", "predicate", "query"): + if inputs["$defs"][name] != outputs["$defs"][name]: + raise ValueError(f"Request and replacement query definitions differ: {name}") + version = outputs["properties"]["contract_version"]["const"] + query = { + "$schema": inputs["$schema"], + "$ref": "#/$defs/query", + "$defs": {key: inputs["$defs"][key] for key in ("expression", "projection", "predicate", "query")}, + } + files = {} + for name, schema in (("input", inputs), ("output", outputs), ("query", query)): + schema = { + "$comment": LICENSE + " Generated by scripts/generate-mcp-profile.py; do not edit.", + "$id": f"urn:apache:ossie:execute-query:{name}:{version}", + **schema, + } + files[f"execute-query-{name}.schema.json"] = json.dumps(schema, indent=2) + "\n" + arguments = next(block for block in blocks if "data_source_id" in block) + result = next(block for block in blocks if block.get("structuredContent", {}).get("status") == "success") + error = next(block for block in blocks if block.get("structuredContent", {}).get("status") == "error") + invalid = {"data_source_id": arguments["data_source_id"], "query": {"measures": ["total_reveneu"]}} + capture = { + "$comment": LICENSE + " Generated example capture, not a real engine execution.", + "protocol_version": "2026-07-28", + "tool": {"name": "execute_query", "inputSchema": inputs, "outputSchema": outputs}, + "cases": [ + {"name": "example success", "arguments": arguments, "result": result}, + {"name": "example semantic refusal", "arguments": invalid, "result": error}, + ], + } + files["example-capture.json"] = json.dumps(capture, indent=2) + "\n" + return files + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true", help="Report drift without writing") + args = parser.parse_args() + changed = [] + for name, content in generated_files().items(): + path = DESTINATION / name + if path.exists() and path.read_text(encoding="utf-8") == content: + continue + changed.append(name) + if not args.check: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8", newline="\n") + if args.check and changed: + print("Generated MCP profile files are out of date: " + ", ".join(changed)) + return 1 + print("MCP profile files " + ("updated" if changed else "are in sync")) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/validation/mcp/README.md b/validation/mcp/README.md new file mode 100644 index 000000000..02164ad4f --- /dev/null +++ b/validation/mcp/README.md @@ -0,0 +1,128 @@ + + +# MCP endpoint contract checks + +Implementor tooling for the proposed +[`execute_query` profile](../../docs/proposals/execute-query-mcp.md), version +`0.4-draft`. It checks the **MCP tool declaration and captured observable +contract**, not a query compiler, an engine or an adopted Ossie standard. +An engine's integration tests can collect these captures without changing its +implementation language. + +## Reusable schemas + +| Artifact | Purpose | +| --- | --- | +| `execute-query-input.schema.json` | Publish as the tool's `inputSchema`; accepts `{data_source_id, query}`. | +| `execute-query-output.schema.json` | Publish as `outputSchema` for structured results, including semantic errors and object-valued repair queries. | +| `execute-query-query.schema.json` | Validate the Layer 3 object independently; uses the same definitions as requests and repairs. | +| `call-result.schema.json` | Ossie constraints on a final MCP result: text/resource content, explicit status and optional structured data. Not the complete MCP protocol schema. | +| `capture.schema.json` | Offline test-harness capture format; not a new endpoint or RPC. | + +The first three schemas and `example-capture.json` are generated from the +profile's schema/example blocks, preventing documentation and implementation +contracts from drifting. Their `urn:` identifiers are offline schema identities, +not download URLs. Resolve the provided files locally; never fetch captured +schema references over the network. + +```sh +python scripts/generate-mcp-profile.py # refresh generated files +python scripts/generate-mcp-profile.py --check # CI drift check +``` + +## Checking an endpoint + +Copy its `execute_query` entry from `tools/list` and capture final results from +your SDK/client. Strip JSON-RPC wrappers: `arguments` is the `tools/call` +argument object; `result` is the final `CallToolResult`. For a completed Task, +capture the final nested tool result, not the initial Task handle. + +```json +{ + "protocol_version": "2026-07-28", + "tool": { + "name": "execute_query", + "inputSchema": {} + }, + "cases": [{ + "name": "replace with a real captured exchange", + "arguments": { + "data_source_id": "sales-model", + "query": {"measures": ["total_revenue"]} + }, + "result": {} + }] +} +``` + +The empty schemas/result above are placeholders, **not a conforming capture**. +Use `example-capture.json` for a complete generated illustration: + +```sh +uv run validation/validate_mcp.py validation/mcp/example-capture.json +uv run validation/validate_mcp.py path/to/endpoint-capture.json +``` + +With `jsonschema` already installed, `python` works in place of `uv run`. +The CLI reads at most 16 MiB, rejects duplicate JSON keys/non-finite constants, +prints a JSON report, and performs no network requests or query execution. +Do not commit captures containing private query results or credentials. + +| Exit / status | Meaning within the reported scope | +| --- | --- | +| `0` / `passed` | Recognized declarations and supplied exchanges passed the observable contract checks. | +| `1` / `failed` | A concrete violation, malformed capture or invalid schema was found; JSON Pointer findings identify the surface. | +| `2` / `unverified` | Declaration equivalence, Markdown-only interpretation or an opaque encoding could not be established. Never treat this as a pass. | + +The library entry point is `validate_capture(capture)`. Its report includes +`profile`, `scope`, `cases_checked`, `findings`, `unverified` and **`unchecked`**. +CI should require exit zero and review unchecked obligations separately. + +## What the checker establishes + +- Tool name and valid schema declarations; recognizes the published input/output + schemas including local reference expansion, reordered set-like keywords and + annotation changes. It does **not** claim to prove arbitrary JSON Schema + equivalence: other schemas are explicitly unverified. +- Requests outside the input contract cannot receive success; result objects + match the published profile, repairs use the query schema, and `isError`, + structured status, source and model/revision consistency agree. +- Success descriptors refer to actual embedded resources, not link-only + substitutes; CSV headers, arity, materialized counts, completeness and metadata + agree. Null/empty/string escaping, exact numeric strings and locale-neutral + date/time encodings are checked. +- Preview rows/counts/types match embedded CSV, including sample membership, + duplicate rows/names, and first-row ordering when declared. Omitted previews + are valid. Binary payloads must be base64, with correct declared export MIME + types; this does not prove the file is valid XLSX/Parquet. + +The report does **not** certify Foundation query answers, semantic-code triggers, +authorization/RLS/OLS, read-only enforcement, invisible retries/probes, live +transport/discovery, Task lifecycle, server budgets, natural-language prose +meaning or binary file fidelity. A captured source's real model identity needs +independent discovery/engine evidence. Passing one fixture proves only that +fixture, not every behavior of an endpoint. + +Recommended integration cases: aggregation/scalar success; header-only zero +rows; invalid shapes; semantic refusals; unsupported capabilities; null/empty, +large integer/decimal and Unicode values; optional previews; resource limits; +and the final output from synchronous and Task execution. Use the official MCP +conformance tooling for protocol lifecycle, and Foundation semantic fixtures +for engine answers; neither replaces these Ossie-specific output checks. diff --git a/validation/mcp/call-result.schema.json b/validation/mcp/call-result.schema.json new file mode 100644 index 000000000..a50b34db3 --- /dev/null +++ b/validation/mcp/call-result.schema.json @@ -0,0 +1,41 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:apache:ossie:execute-query:call-result:0.4-draft", + "$comment": "Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See NOTICE for copyright ownership. Licensed under the Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 . Distributed on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND. This is an Ossie final-result constraint, not a replacement for the full MCP protocol schema.", + "type": "object", + "required": ["resultType", "content", "isError"], + "properties": { + "_meta": {"type": "object"}, + "resultType": {"const": "complete"}, + "isError": {"type": "boolean"}, + "structuredContent": {"$ref": "urn:apache:ossie:execute-query:output:0.4-draft"}, + "content": { + "type": "array", "minItems": 1, + "contains": {"type": "object", "required": ["type", "text"], "properties": {"type": {"const": "text"}, "text": {"type": "string", "pattern": "\\S"}}}, + "items": { + "oneOf": [ + {"type": "object", "required": ["type", "text"], "properties": {"type": {"const": "text"}, "text": {"type": "string"}}}, + {"type": "object", "required": ["type", "resource"], "properties": {"type": {"const": "resource"}, "resource": {"$ref": "#/$defs/embedded"}}}, + {"type": "object", "required": ["type", "uri", "name"], "properties": {"type": {"const": "resource_link"}, "uri": {"type": "string", "format": "uri"}, "name": {"type": "string"}}}, + {"type": "object", "required": ["type", "data", "mimeType"], "properties": {"type": {"enum": ["image", "audio"]}, "data": {"type": "string"}, "mimeType": {"type": "string"}}} + ] + } + } + }, + "$defs": { + "embedded": { + "type": "object", "required": ["uri", "mimeType"], + "properties": { + "_meta": {"type": "object"}, + "uri": {"type": "string", "format": "uri"}, + "mimeType": {"type": "string"}, + "text": {"type": "string"}, + "blob": {"type": "string"} + }, + "oneOf": [ + {"required": ["text"], "not": {"required": ["blob"]}}, + {"required": ["blob"], "not": {"required": ["text"]}} + ] + } + } +} diff --git a/validation/mcp/capture.schema.json b/validation/mcp/capture.schema.json new file mode 100644 index 000000000..fbb0fa3be --- /dev/null +++ b/validation/mcp/capture.schema.json @@ -0,0 +1,44 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:apache:ossie:execute-query:capture:0.4-draft", + "$comment": "Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See NOTICE for copyright ownership. Licensed under the Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 . Distributed on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND. Capture format for offline endpoint contract checks; not an MCP RPC.", + "type": "object", "additionalProperties": false, + "required": ["protocol_version", "tool", "cases"], + "properties": { + "$comment": {"type": "string"}, + "protocol_version": {"const": "2026-07-28"}, + "tool": { + "type": "object", "required": ["name", "inputSchema"], + "properties": { + "name": {"const": "execute_query"}, + "title": {"type": "string"}, + "description": {"type": "string"}, + "_meta": {"type": "object"}, + "inputSchema": {"type": "object"}, + "outputSchema": {"type": "object"}, + "annotations": { + "type": "object", + "properties": { + "title": {"type": "string"}, + "readOnlyHint": {"type": "boolean"}, + "destructiveHint": {"type": "boolean"}, + "idempotentHint": {"type": "boolean"}, + "openWorldHint": {"type": "boolean"} + } + } + } + }, + "cases": { + "type": "array", "minItems": 1, + "items": { + "type": "object", "additionalProperties": false, + "required": ["arguments", "result"], + "properties": { + "name": {"type": "string"}, + "arguments": {"type": "object"}, + "result": {"$ref": "urn:apache:ossie:execute-query:call-result:0.4-draft"} + } + } + } + } +} diff --git a/validation/mcp/example-capture.json b/validation/mcp/example-capture.json new file mode 100644 index 000000000..8a4d2bcdb --- /dev/null +++ b/validation/mcp/example-capture.json @@ -0,0 +1,874 @@ +{ + "$comment": "Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See NOTICE for copyright ownership. Licensed under the Apache License, Version 2.0; http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, distributed on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND. Generated example capture, not a real engine execution.", + "protocol_version": "2026-07-28", + "tool": { + "name": "execute_query", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "additionalProperties": false, + "required": [ + "data_source_id", + "query" + ], + "properties": { + "data_source_id": { + "type": "string", + "minLength": 1, + "pattern": "\\S" + }, + "query": { + "$ref": "#/$defs/query" + } + }, + "$defs": { + "expression": { + "type": "string", + "minLength": 1, + "pattern": "\\S" + }, + "projection": { + "type": "array", + "items": { + "$ref": "#/$defs/expression" + } + }, + "predicate": { + "oneOf": [ + { + "$ref": "#/$defs/expression" + }, + { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/expression" + } + } + ] + }, + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "dimensions": { + "$ref": "#/$defs/projection" + }, + "measures": { + "$ref": "#/$defs/projection" + }, + "fields": { + "allOf": [ + { + "$ref": "#/$defs/projection" + } + ], + "minItems": 1 + }, + "where": { + "$ref": "#/$defs/predicate" + }, + "having": { + "$ref": "#/$defs/predicate" + }, + "order_by": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "field" + ], + "properties": { + "field": { + "$ref": "#/$defs/expression" + }, + "direction": { + "enum": [ + "ASC", + "DESC" + ] + }, + "nulls": { + "enum": [ + "FIRST", + "LAST" + ] + } + } + } + }, + "limit": { + "type": "integer", + "minimum": 0 + } + }, + "oneOf": [ + { + "not": { + "required": [ + "fields" + ] + }, + "anyOf": [ + { + "required": [ + "dimensions" + ], + "properties": { + "dimensions": { + "minItems": 1 + } + } + }, + { + "required": [ + "measures" + ], + "properties": { + "measures": { + "minItems": 1 + } + } + } + ] + }, + { + "required": [ + "fields" + ], + "not": { + "anyOf": [ + { + "required": [ + "dimensions" + ] + }, + { + "required": [ + "measures" + ] + }, + { + "required": [ + "having" + ] + } + ] + } + } + ] + } + } + }, + "outputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "additionalProperties": false, + "required": [ + "contract_version", + "status", + "diagnostics", + "suggestions", + "filter_value_alternatives" + ], + "properties": { + "contract_version": { + "const": "0.4-draft" + }, + "status": { + "enum": [ + "success", + "error" + ] + }, + "data_source_id": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "revision" + ], + "properties": { + "id": { + "type": "string", + "minLength": 1 + }, + "revision": { + "type": "string", + "minLength": 1 + } + } + }, + "preview": { + "type": "object", + "additionalProperties": false, + "required": [ + "columns", + "rows", + "row_count", + "has_more" + ], + "properties": { + "columns": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "datatype": { + "enum": [ + "String", + "Integer", + "Decimal", + "Float", + "Boolean", + "Date", + "Time", + "DateTime", + "DateTimeTz", + "Opaque" + ] + } + } + } + }, + "rows": { + "type": "array", + "items": { + "type": "array", + "items": {} + } + }, + "row_count": { + "type": "integer", + "minimum": 0 + }, + "has_more": { + "type": "boolean" + }, + "selection": { + "enum": [ + "first_rows", + "sample" + ] + } + } + }, + "result": { + "type": "object", + "additionalProperties": false, + "required": [ + "row_count", + "completeness", + "resources" + ], + "properties": { + "row_count": { + "type": "integer", + "minimum": 0 + }, + "completeness": { + "enum": [ + "complete", + "truncated", + "unknown" + ] + }, + "resources": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/resource" + }, + "contains": { + "type": "object", + "required": [ + "format" + ], + "properties": { + "format": { + "const": "csv" + } + } + } + }, + "extensions": { + "$ref": "#/$defs/extensions" + } + } + }, + "error": { + "type": "object", + "additionalProperties": false, + "required": [ + "code", + "message", + "retryable" + ], + "properties": { + "code": { + "type": "string", + "minLength": 1 + }, + "message": { + "type": "string", + "minLength": 1 + }, + "retryable": { + "type": "boolean" + }, + "extensions": { + "$ref": "#/$defs/extensions" + } + } + }, + "diagnostics": { + "type": "object", + "additionalProperties": false, + "required": [ + "state" + ], + "properties": { + "state": { + "enum": [ + "completed", + "partial", + "unavailable", + "not_applicable" + ] + }, + "message": { + "type": "string", + "minLength": 1 + }, + "extensions": { + "$ref": "#/$defs/extensions" + } + }, + "if": { + "properties": { + "state": { + "enum": [ + "partial", + "unavailable" + ] + } + } + }, + "then": { + "required": [ + "message" + ] + } + }, + "suggestions": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "kind", + "message" + ], + "properties": { + "kind": { + "type": "string", + "minLength": 1 + }, + "message": { + "type": "string", + "minLength": 1 + }, + "replacement_query": { + "$ref": "#/$defs/query" + }, + "extensions": { + "$ref": "#/$defs/extensions" + } + } + } + }, + "filter_value_alternatives": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "field", + "requested_value", + "values", + "match", + "complete" + ], + "properties": { + "field": { + "type": "string", + "minLength": 1 + }, + "requested_value": {}, + "values": { + "type": "array", + "items": {} + }, + "match": { + "enum": [ + "exact", + "fuzzy", + "unknown" + ] + }, + "complete": { + "type": "boolean" + }, + "extensions": { + "$ref": "#/$defs/extensions" + } + } + } + }, + "extensions": { + "$ref": "#/$defs/extensions" + } + }, + "$defs": { + "expression": { + "type": "string", + "minLength": 1, + "pattern": "\\S" + }, + "projection": { + "type": "array", + "items": { + "$ref": "#/$defs/expression" + } + }, + "predicate": { + "oneOf": [ + { + "$ref": "#/$defs/expression" + }, + { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/expression" + } + } + ] + }, + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "dimensions": { + "$ref": "#/$defs/projection" + }, + "measures": { + "$ref": "#/$defs/projection" + }, + "fields": { + "allOf": [ + { + "$ref": "#/$defs/projection" + } + ], + "minItems": 1 + }, + "where": { + "$ref": "#/$defs/predicate" + }, + "having": { + "$ref": "#/$defs/predicate" + }, + "order_by": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "field" + ], + "properties": { + "field": { + "$ref": "#/$defs/expression" + }, + "direction": { + "enum": [ + "ASC", + "DESC" + ] + }, + "nulls": { + "enum": [ + "FIRST", + "LAST" + ] + } + } + } + }, + "limit": { + "type": "integer", + "minimum": 0 + } + }, + "oneOf": [ + { + "not": { + "required": [ + "fields" + ] + }, + "anyOf": [ + { + "required": [ + "dimensions" + ], + "properties": { + "dimensions": { + "minItems": 1 + } + } + }, + { + "required": [ + "measures" + ], + "properties": { + "measures": { + "minItems": 1 + } + } + } + ] + }, + { + "required": [ + "fields" + ], + "not": { + "anyOf": [ + { + "required": [ + "dimensions" + ] + }, + { + "required": [ + "measures" + ] + }, + { + "required": [ + "having" + ] + } + ] + } + } + ] + }, + "extensions": { + "type": "object", + "additionalProperties": { + "type": "object" + } + }, + "resource": { + "type": "object", + "additionalProperties": false, + "required": [ + "uri", + "name", + "format", + "mime_type" + ], + "properties": { + "uri": { + "type": "string", + "format": "uri" + }, + "name": { + "type": "string", + "minLength": 1 + }, + "format": { + "type": "string", + "minLength": 1 + }, + "mime_type": { + "type": "string", + "minLength": 1 + }, + "csv_null_value": { + "const": "\\N" + }, + "csv_escape_prefix": { + "const": "\\" + }, + "extensions": { + "$ref": "#/$defs/extensions" + } + }, + "if": { + "properties": { + "format": { + "const": "csv" + } + } + }, + "then": { + "required": [ + "csv_null_value", + "csv_escape_prefix" + ], + "properties": { + "mime_type": { + "const": "text/csv" + } + } + } + } + }, + "oneOf": [ + { + "properties": { + "status": { + "const": "success" + } + }, + "required": [ + "data_source_id", + "model", + "result" + ], + "not": { + "required": [ + "error" + ] + } + }, + { + "properties": { + "status": { + "const": "error" + } + }, + "required": [ + "error" + ], + "not": { + "anyOf": [ + { + "required": [ + "preview" + ] + }, + { + "required": [ + "result" + ] + } + ] + } + } + ] + } + }, + "cases": [ + { + "name": "example success", + "arguments": { + "data_source_id": "sales-model", + "query": { + "dimensions": [ + "customers.region" + ], + "measures": [ + "total_revenue" + ], + "where": "orders.status = 'completed'", + "order_by": [ + { + "field": "total_revenue", + "direction": "DESC", + "nulls": "LAST" + } + ], + "limit": 20 + } + }, + "result": { + "resultType": "complete", + "isError": false, + "content": [ + { + "type": "text", + "text": "1 row; complete. Data: sales.csv. No applicable filter guidance." + }, + { + "type": "resource", + "resource": { + "uri": "file:///sales.csv", + "mimeType": "text/csv", + "text": "region,total_revenue\r\nWest,12345.67\r\n", + "_meta": { + "org.apache.ossie/execute_query": { + "columns": [ + { + "name": "region", + "datatype": "String" + }, + { + "name": "total_revenue", + "datatype": "Decimal" + } + ], + "row_count": 1, + "completeness": "complete", + "csv_null_value": "\\N", + "csv_escape_prefix": "\\" + } + } + }, + "annotations": { + "audience": [ + "user", + "assistant" + ] + } + } + ], + "structuredContent": { + "contract_version": "0.4-draft", + "status": "success", + "data_source_id": "sales-model", + "model": { + "id": "sales", + "revision": "r1" + }, + "preview": { + "columns": [ + { + "name": "region", + "datatype": "String" + }, + { + "name": "total_revenue", + "datatype": "Decimal" + } + ], + "rows": [ + [ + "West", + "12345.67" + ] + ], + "row_count": 1, + "has_more": false + }, + "result": { + "row_count": 1, + "completeness": "complete", + "resources": [ + { + "uri": "file:///sales.csv", + "name": "sales.csv", + "format": "csv", + "mime_type": "text/csv", + "csv_null_value": "\\N", + "csv_escape_prefix": "\\" + } + ] + }, + "diagnostics": { + "state": "not_applicable" + }, + "suggestions": [], + "filter_value_alternatives": [] + } + } + }, + { + "name": "example semantic refusal", + "arguments": { + "data_source_id": "sales-model", + "query": { + "measures": [ + "total_reveneu" + ] + } + }, + "result": { + "resultType": "complete", + "isError": true, + "content": [ + { + "type": "text", + "text": "Unknown metric `total_reveneu`; use `total_revenue`. No replacement query executed." + } + ], + "structuredContent": { + "contract_version": "0.4-draft", + "status": "error", + "data_source_id": "sales-model", + "model": { + "id": "sales", + "revision": "r1" + }, + "error": { + "code": "E_NAME_NOT_FOUND", + "message": "Unknown metric 'total_reveneu'; did you mean 'total_revenue'?", + "retryable": false, + "extensions": { + "example.org/parser": { + "line": 1 + } + } + }, + "diagnostics": { + "state": "completed" + }, + "suggestions": [ + { + "kind": "query", + "message": "Use the known total_revenue metric.", + "replacement_query": { + "dimensions": [ + "customers.region" + ], + "measures": [ + "total_revenue" + ], + "where": "orders.status = 'completed'", + "order_by": [ + { + "field": "total_revenue", + "direction": "DESC", + "nulls": "LAST" + } + ], + "limit": 20 + } + } + ], + "filter_value_alternatives": [] + } + } + } + ] +} diff --git a/validation/mcp/execute-query-input.schema.json b/validation/mcp/execute-query-input.schema.json new file mode 100644 index 000000000..6f6a184d3 --- /dev/null +++ b/validation/mcp/execute-query-input.schema.json @@ -0,0 +1,161 @@ +{ + "$comment": "Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See NOTICE for copyright ownership. Licensed under the Apache License, Version 2.0; http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, distributed on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND. Generated by scripts/generate-mcp-profile.py; do not edit.", + "$id": "urn:apache:ossie:execute-query:input:0.4-draft", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "additionalProperties": false, + "required": [ + "data_source_id", + "query" + ], + "properties": { + "data_source_id": { + "type": "string", + "minLength": 1, + "pattern": "\\S" + }, + "query": { + "$ref": "#/$defs/query" + } + }, + "$defs": { + "expression": { + "type": "string", + "minLength": 1, + "pattern": "\\S" + }, + "projection": { + "type": "array", + "items": { + "$ref": "#/$defs/expression" + } + }, + "predicate": { + "oneOf": [ + { + "$ref": "#/$defs/expression" + }, + { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/expression" + } + } + ] + }, + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "dimensions": { + "$ref": "#/$defs/projection" + }, + "measures": { + "$ref": "#/$defs/projection" + }, + "fields": { + "allOf": [ + { + "$ref": "#/$defs/projection" + } + ], + "minItems": 1 + }, + "where": { + "$ref": "#/$defs/predicate" + }, + "having": { + "$ref": "#/$defs/predicate" + }, + "order_by": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "field" + ], + "properties": { + "field": { + "$ref": "#/$defs/expression" + }, + "direction": { + "enum": [ + "ASC", + "DESC" + ] + }, + "nulls": { + "enum": [ + "FIRST", + "LAST" + ] + } + } + } + }, + "limit": { + "type": "integer", + "minimum": 0 + } + }, + "oneOf": [ + { + "not": { + "required": [ + "fields" + ] + }, + "anyOf": [ + { + "required": [ + "dimensions" + ], + "properties": { + "dimensions": { + "minItems": 1 + } + } + }, + { + "required": [ + "measures" + ], + "properties": { + "measures": { + "minItems": 1 + } + } + } + ] + }, + { + "required": [ + "fields" + ], + "not": { + "anyOf": [ + { + "required": [ + "dimensions" + ] + }, + { + "required": [ + "measures" + ] + }, + { + "required": [ + "having" + ] + } + ] + } + } + ] + } + } +} diff --git a/validation/mcp/execute-query-output.schema.json b/validation/mcp/execute-query-output.schema.json new file mode 100644 index 000000000..e741bab48 --- /dev/null +++ b/validation/mcp/execute-query-output.schema.json @@ -0,0 +1,528 @@ +{ + "$comment": "Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See NOTICE for copyright ownership. Licensed under the Apache License, Version 2.0; http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, distributed on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND. Generated by scripts/generate-mcp-profile.py; do not edit.", + "$id": "urn:apache:ossie:execute-query:output:0.4-draft", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "additionalProperties": false, + "required": [ + "contract_version", + "status", + "diagnostics", + "suggestions", + "filter_value_alternatives" + ], + "properties": { + "contract_version": { + "const": "0.4-draft" + }, + "status": { + "enum": [ + "success", + "error" + ] + }, + "data_source_id": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "revision" + ], + "properties": { + "id": { + "type": "string", + "minLength": 1 + }, + "revision": { + "type": "string", + "minLength": 1 + } + } + }, + "preview": { + "type": "object", + "additionalProperties": false, + "required": [ + "columns", + "rows", + "row_count", + "has_more" + ], + "properties": { + "columns": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "datatype": { + "enum": [ + "String", + "Integer", + "Decimal", + "Float", + "Boolean", + "Date", + "Time", + "DateTime", + "DateTimeTz", + "Opaque" + ] + } + } + } + }, + "rows": { + "type": "array", + "items": { + "type": "array", + "items": {} + } + }, + "row_count": { + "type": "integer", + "minimum": 0 + }, + "has_more": { + "type": "boolean" + }, + "selection": { + "enum": [ + "first_rows", + "sample" + ] + } + } + }, + "result": { + "type": "object", + "additionalProperties": false, + "required": [ + "row_count", + "completeness", + "resources" + ], + "properties": { + "row_count": { + "type": "integer", + "minimum": 0 + }, + "completeness": { + "enum": [ + "complete", + "truncated", + "unknown" + ] + }, + "resources": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/resource" + }, + "contains": { + "type": "object", + "required": [ + "format" + ], + "properties": { + "format": { + "const": "csv" + } + } + } + }, + "extensions": { + "$ref": "#/$defs/extensions" + } + } + }, + "error": { + "type": "object", + "additionalProperties": false, + "required": [ + "code", + "message", + "retryable" + ], + "properties": { + "code": { + "type": "string", + "minLength": 1 + }, + "message": { + "type": "string", + "minLength": 1 + }, + "retryable": { + "type": "boolean" + }, + "extensions": { + "$ref": "#/$defs/extensions" + } + } + }, + "diagnostics": { + "type": "object", + "additionalProperties": false, + "required": [ + "state" + ], + "properties": { + "state": { + "enum": [ + "completed", + "partial", + "unavailable", + "not_applicable" + ] + }, + "message": { + "type": "string", + "minLength": 1 + }, + "extensions": { + "$ref": "#/$defs/extensions" + } + }, + "if": { + "properties": { + "state": { + "enum": [ + "partial", + "unavailable" + ] + } + } + }, + "then": { + "required": [ + "message" + ] + } + }, + "suggestions": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "kind", + "message" + ], + "properties": { + "kind": { + "type": "string", + "minLength": 1 + }, + "message": { + "type": "string", + "minLength": 1 + }, + "replacement_query": { + "$ref": "#/$defs/query" + }, + "extensions": { + "$ref": "#/$defs/extensions" + } + } + } + }, + "filter_value_alternatives": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "field", + "requested_value", + "values", + "match", + "complete" + ], + "properties": { + "field": { + "type": "string", + "minLength": 1 + }, + "requested_value": {}, + "values": { + "type": "array", + "items": {} + }, + "match": { + "enum": [ + "exact", + "fuzzy", + "unknown" + ] + }, + "complete": { + "type": "boolean" + }, + "extensions": { + "$ref": "#/$defs/extensions" + } + } + } + }, + "extensions": { + "$ref": "#/$defs/extensions" + } + }, + "$defs": { + "expression": { + "type": "string", + "minLength": 1, + "pattern": "\\S" + }, + "projection": { + "type": "array", + "items": { + "$ref": "#/$defs/expression" + } + }, + "predicate": { + "oneOf": [ + { + "$ref": "#/$defs/expression" + }, + { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/expression" + } + } + ] + }, + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "dimensions": { + "$ref": "#/$defs/projection" + }, + "measures": { + "$ref": "#/$defs/projection" + }, + "fields": { + "allOf": [ + { + "$ref": "#/$defs/projection" + } + ], + "minItems": 1 + }, + "where": { + "$ref": "#/$defs/predicate" + }, + "having": { + "$ref": "#/$defs/predicate" + }, + "order_by": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "field" + ], + "properties": { + "field": { + "$ref": "#/$defs/expression" + }, + "direction": { + "enum": [ + "ASC", + "DESC" + ] + }, + "nulls": { + "enum": [ + "FIRST", + "LAST" + ] + } + } + } + }, + "limit": { + "type": "integer", + "minimum": 0 + } + }, + "oneOf": [ + { + "not": { + "required": [ + "fields" + ] + }, + "anyOf": [ + { + "required": [ + "dimensions" + ], + "properties": { + "dimensions": { + "minItems": 1 + } + } + }, + { + "required": [ + "measures" + ], + "properties": { + "measures": { + "minItems": 1 + } + } + } + ] + }, + { + "required": [ + "fields" + ], + "not": { + "anyOf": [ + { + "required": [ + "dimensions" + ] + }, + { + "required": [ + "measures" + ] + }, + { + "required": [ + "having" + ] + } + ] + } + } + ] + }, + "extensions": { + "type": "object", + "additionalProperties": { + "type": "object" + } + }, + "resource": { + "type": "object", + "additionalProperties": false, + "required": [ + "uri", + "name", + "format", + "mime_type" + ], + "properties": { + "uri": { + "type": "string", + "format": "uri" + }, + "name": { + "type": "string", + "minLength": 1 + }, + "format": { + "type": "string", + "minLength": 1 + }, + "mime_type": { + "type": "string", + "minLength": 1 + }, + "csv_null_value": { + "const": "\\N" + }, + "csv_escape_prefix": { + "const": "\\" + }, + "extensions": { + "$ref": "#/$defs/extensions" + } + }, + "if": { + "properties": { + "format": { + "const": "csv" + } + } + }, + "then": { + "required": [ + "csv_null_value", + "csv_escape_prefix" + ], + "properties": { + "mime_type": { + "const": "text/csv" + } + } + } + } + }, + "oneOf": [ + { + "properties": { + "status": { + "const": "success" + } + }, + "required": [ + "data_source_id", + "model", + "result" + ], + "not": { + "required": [ + "error" + ] + } + }, + { + "properties": { + "status": { + "const": "error" + } + }, + "required": [ + "error" + ], + "not": { + "anyOf": [ + { + "required": [ + "preview" + ] + }, + { + "required": [ + "result" + ] + } + ] + } + } + ] +} diff --git a/validation/mcp/execute-query-query.schema.json b/validation/mcp/execute-query-query.schema.json new file mode 100644 index 000000000..7c1b07ce6 --- /dev/null +++ b/validation/mcp/execute-query-query.schema.json @@ -0,0 +1,146 @@ +{ + "$comment": "Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See NOTICE for copyright ownership. Licensed under the Apache License, Version 2.0; http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, distributed on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND. Generated by scripts/generate-mcp-profile.py; do not edit.", + "$id": "urn:apache:ossie:execute-query:query:0.4-draft", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$ref": "#/$defs/query", + "$defs": { + "expression": { + "type": "string", + "minLength": 1, + "pattern": "\\S" + }, + "projection": { + "type": "array", + "items": { + "$ref": "#/$defs/expression" + } + }, + "predicate": { + "oneOf": [ + { + "$ref": "#/$defs/expression" + }, + { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/expression" + } + } + ] + }, + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "dimensions": { + "$ref": "#/$defs/projection" + }, + "measures": { + "$ref": "#/$defs/projection" + }, + "fields": { + "allOf": [ + { + "$ref": "#/$defs/projection" + } + ], + "minItems": 1 + }, + "where": { + "$ref": "#/$defs/predicate" + }, + "having": { + "$ref": "#/$defs/predicate" + }, + "order_by": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "field" + ], + "properties": { + "field": { + "$ref": "#/$defs/expression" + }, + "direction": { + "enum": [ + "ASC", + "DESC" + ] + }, + "nulls": { + "enum": [ + "FIRST", + "LAST" + ] + } + } + } + }, + "limit": { + "type": "integer", + "minimum": 0 + } + }, + "oneOf": [ + { + "not": { + "required": [ + "fields" + ] + }, + "anyOf": [ + { + "required": [ + "dimensions" + ], + "properties": { + "dimensions": { + "minItems": 1 + } + } + }, + { + "required": [ + "measures" + ], + "properties": { + "measures": { + "minItems": 1 + } + } + } + ] + }, + { + "required": [ + "fields" + ], + "not": { + "anyOf": [ + { + "required": [ + "dimensions" + ] + }, + { + "required": [ + "measures" + ] + }, + { + "required": [ + "having" + ] + } + ] + } + } + ] + } + } +} diff --git a/validation/tests/test_validate_mcp.py b/validation/tests/test_validate_mcp.py new file mode 100644 index 000000000..0360c567f --- /dev/null +++ b/validation/tests/test_validate_mcp.py @@ -0,0 +1,324 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import copy +import json +import subprocess +import sys +import urllib.request +from importlib.util import module_from_spec, spec_from_file_location +from pathlib import Path + +import pytest + +pytest.importorskip("jsonschema") +ROOT = Path(__file__).resolve().parents[2] +SPEC = spec_from_file_location("validate_mcp", ROOT / "validation/validate_mcp.py") +VALIDATOR = module_from_spec(SPEC) +SPEC.loader.exec_module(VALIDATOR) + + +@pytest.fixture +def capture(): + return json.loads((ROOT / "validation/mcp/example-capture.json").read_text(encoding="utf-8")) + + +def success(capture): + return capture["cases"][0]["result"] + + +def payload(capture): + return success(capture)["structuredContent"] + + +def resource(capture): + return success(capture)["content"][1]["resource"] + + +def codes(report): + return {finding["code"] for finding in report["findings"]} + + +def test_published_example_passes_with_explicit_unchecked_scope(capture): + report = VALIDATOR.validate_capture(capture) + assert report["status"] == "passed" + assert report["cases_checked"] == 2 + assert report["scope"] == "captured MCP endpoint contract" + assert "authorization" in " ".join(report["unchecked"]) + assert "grain" in " ".join(report["unchecked"]) + + +def test_generation_has_no_drift(): + result = subprocess.run( + [sys.executable, str(ROOT / "scripts/generate-mcp-profile.py"), "--check"], + cwd=ROOT, capture_output=True, text=True, + ) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize("change", [ + lambda c: c.update(protocol_version="2025-11-25"), + lambda c: c.update(cases=[]), + lambda c: c["tool"].update(name="native_execute"), + lambda c: c["tool"].update(annotations={"readOnlyHint": "true"}), + lambda c: success(c).pop("resultType"), + lambda c: success(c).pop("isError"), + lambda c: success(c).update(resultType="task"), + lambda c: resource(c).update(text=42), + lambda c: resource(c).update(blob="ZGF0YQ=="), + lambda c: resource(c).update(_meta=None), + lambda c: payload(c).update(contract_version="0.3-draft"), + lambda c: payload(c).pop("model"), + lambda c: payload(c)["diagnostics"].update(state="partial"), + lambda c: c["cases"][1]["result"]["structuredContent"]["suggestions"][0].update(replacement_query="SELECT 1"), +]) +def test_schema_violations_fail(capture, change): + change(capture) + report = VALIDATOR.validate_capture(capture) + assert report["status"] == "failed" + assert "CONTRACT_SCHEMA" in codes(report) + + +@pytest.mark.parametrize(("change", "expected"), [ + (lambda c: c["cases"][0]["arguments"].update(query="SELECT 1"), "INVALID_INPUT_ACCEPTED"), + (lambda c: success(c).update(isError=True), "STATUS_MISMATCH"), + (lambda c: payload(c).update(data_source_id="another-model"), "SOURCE_MISMATCH"), + (lambda c: resource(c).update(mimeType="text/plain"), "RESOURCE_MISMATCH"), + (lambda c: resource(c).update(text="wrong,header\r\nWest,12345.67\r\n"), "CSV_HEADER"), + (lambda c: resource(c).update(text="region,total_revenue\r\nWest\r\n"), "CSV_ARITY"), + (lambda c: resource(c).update(text="region,total_revenue\r\n"), "CSV_ROW_COUNT"), + (lambda c: resource(c).update(text='region,total_revenue\r\n"unclosed'), "INVALID_CSV"), + (lambda c: payload(c)["preview"].update(row_count=2), "PREVIEW_ROW_COUNT"), + (lambda c: payload(c)["preview"].update(has_more=True), "PREVIEW_COMPLETENESS"), + (lambda c: payload(c)["preview"].update(rows=[["West"]]), "PREVIEW_ARITY"), + (lambda c: payload(c)["preview"].update(rows=[["East", "12345.67"]]), "PREVIEW_VALUES"), + (lambda c: payload(c)["preview"].update(rows=[["West", 12345.67]]), "VALUE_ENCODING"), + (lambda c: payload(c)["preview"].update(rows=[["West", "12,345.67"]]), "VALUE_ENCODING"), + (lambda c: payload(c)["preview"]["columns"][0].update(name="other"), "PREVIEW_COLUMNS"), + (lambda c: resource(c)["_meta"][VALIDATOR.METADATA].update(completeness="truncated"), "CSV_METADATA_MISMATCH"), + (lambda c: success(c)["content"].pop(1), "MISSING_EMBEDDED_RESOURCE"), + (lambda c: success(c)["content"].append(copy.deepcopy(success(c)["content"][1])), "DUPLICATE_RESOURCE"), + (lambda c: payload(c)["result"]["resources"].append(copy.deepcopy(payload(c)["result"]["resources"][0])), "DUPLICATE_RESOURCE"), + (lambda c: c["tool"].update(annotations={"readOnlyHint": False}), "READ_ONLY_DECLARATION"), +]) +def test_cross_surface_contract_violations(capture, change, expected): + change(capture) + report = VALIDATOR.validate_capture(capture) + assert report["status"] == "failed" + assert expected in codes(report) + + +def test_missing_resource_metadata_fails(capture): + resource(capture).pop("_meta") + assert VALIDATOR.validate_capture(capture)["status"] == "failed" + + +def test_descriptor_cannot_be_satisfied_by_a_link(capture): + descriptor = payload(capture)["result"]["resources"][0] + success(capture)["content"][1] = { + "type": "resource_link", "uri": descriptor["uri"], "name": descriptor["name"], + } + assert "MISSING_EMBEDDED_RESOURCE" in codes(VALIDATOR.validate_capture(capture)) + + +def test_same_binding_cannot_return_different_model_revisions(capture): + changed = copy.deepcopy(capture["cases"][0]) + changed["result"]["structuredContent"]["model"]["revision"] = "r2" + capture["cases"].append(changed) + assert "MODEL_REBOUND" in codes(VALIDATOR.validate_capture(capture)) + + +def test_input_and_replacement_use_identical_query_schema(capture): + for name in ("expression", "projection", "predicate", "query"): + assert capture["tool"]["inputSchema"]["$defs"][name] == capture["tool"]["outputSchema"]["$defs"][name] + + +def test_schema_annotations_and_local_def_names_do_not_matter(capture): + schema = capture["tool"]["inputSchema"] + schema["description"] = "Vendor implementation" + schema["required"].reverse() + schema["$defs"]["query_copy"] = schema["$defs"].pop("query") + schema["properties"]["query"]["$ref"] = "#/$defs/query_copy" + assert VALIDATOR.validate_capture(capture)["status"] == "passed" + + +def test_unproven_schema_equivalence_is_never_success(capture): + capture["tool"]["inputSchema"] = {"type": "object"} + report = VALIDATOR.validate_capture(capture) + assert report["status"] == "unverified" + assert report["unverified"] + + +def test_invalid_schema_is_explicit_failure(capture): + capture["tool"]["inputSchema"] = {"type": "not-a-json-type"} + assert "INVALID_DECLARATION" in codes(VALIDATOR.validate_capture(capture)) + + +@pytest.mark.parametrize("ref", ["https://example.invalid/schema.json", "#/$defs/loop"]) +def test_schema_normalization_never_retrieves_or_recurses_unboundedly(capture, monkeypatch, ref): + def no_network(*args, **kwargs): + pytest.fail("Captured schemas must not trigger network reads") + monkeypatch.setattr(urllib.request, "urlopen", no_network) + capture["tool"]["inputSchema"] = { + "$ref": ref, "$defs": {"loop": {"$ref": "#/$defs/loop"}}, + } + assert VALIDATOR.validate_capture(capture)["status"] == "unverified" + + +def test_advertised_output_schema_requires_structured_content(capture): + success(capture).pop("structuredContent") + assert "MISSING_STRUCTURED_OUTPUT" in codes(VALIDATOR.validate_capture(capture)) + + +def test_markdown_only_profile_is_explicitly_unverified(capture): + capture["tool"].pop("outputSchema") + for case in capture["cases"]: + case["result"].pop("structuredContent") + assert VALIDATOR.validate_capture(capture)["status"] == "unverified" + + +def test_no_preview_is_valid(capture): + payload(capture).pop("preview") + assert VALIDATOR.validate_capture(capture)["status"] == "passed" + + +def test_scalar_capture_does_not_need_a_semantic_planner(capture): + capture["cases"][0]["arguments"]["query"] = {"fields": ["customers.region"]} + assert VALIDATOR.validate_capture(capture)["status"] == "passed" + + +def test_header_only_zero_rows_are_success(capture): + resource(capture)["text"] = "region,total_revenue\r\n" + resource(capture)["_meta"][VALIDATOR.METADATA]["row_count"] = 0 + payload(capture)["result"]["row_count"] = 0 + payload(capture)["preview"].update(rows=[], row_count=0) + assert VALIDATOR.validate_capture(capture)["status"] == "passed" + + +def test_duplicate_names_nulls_empty_strings_precision_and_escapes(capture): + columns = [{"name": "value", "datatype": "String"}, {"name": "value", "datatype": "Integer"}] + rows = [[None, "9007199254740993"], ["", "2"], [r"\N", "3"]] + resource(capture)["text"] = "value,value\r\n\\N,9007199254740993\r\n,2\r\n\\\\N,3\r\n" + resource(capture)["_meta"][VALIDATOR.METADATA].update(columns=columns, row_count=3) + payload(capture)["result"]["row_count"] = 3 + payload(capture)["preview"].update(columns=columns, rows=rows, row_count=3) + assert VALIDATOR.validate_capture(capture)["status"] == "passed" + + +def test_preview_sample_and_first_rows_have_distinct_order_rules(capture): + resource(capture)["text"] = "region,total_revenue\r\nWest,12345.67\r\nEast,2.00\r\n" + resource(capture)["_meta"][VALIDATOR.METADATA]["row_count"] = 2 + payload(capture)["result"]["row_count"] = 2 + payload(capture)["preview"].update(rows=[["East", "2.00"]], has_more=True, selection="sample") + assert VALIDATOR.validate_capture(capture)["status"] == "passed" + payload(capture)["preview"]["selection"] = "first_rows" + assert "PREVIEW_SELECTION" in codes(VALIDATOR.validate_capture(capture)) + + +@pytest.mark.parametrize(("datatype", "value", "valid"), [ + ("Integer", "9007199254740993", True), + ("Integer", 9007199254740993, False), + ("Decimal", "1234.5600", True), + ("Decimal", "1.234,56", False), + ("Float", float("nan"), False), + ("Float", True, False), + ("Date", "2026-10-09", True), + ("Date", "09/10/2026", False), + ("DateTime", "2026-10-09T10:30:00", True), + ("DateTime", "2026-10-09T10:30:00+02:00", False), + ("DateTimeTz", "2026-10-09T10:30:00+02:00", True), + ("DateTimeTz", "2026-10-09T10:30:00", False), +]) +def test_machine_value_types(datatype, value, valid): + if valid: + assert VALIDATOR._cell(value, datatype) == value + else: + with pytest.raises(ValueError): + VALIDATOR._cell(value, datatype) + + +def test_invalid_binary_base64_fails(capture): + success(capture)["content"].append({ + "type": "resource", + "resource": {"uri": "file:///data.xlsx", "mimeType": "application/octet-stream", "blob": "!"}, + }) + assert "INVALID_BASE64" in codes(VALIDATOR.validate_capture(capture)) + + +def test_nested_schema_ids_cannot_produce_a_false_equivalence_pass(capture): + capture["tool"]["inputSchema"]["$defs"]["query"]["$id"] = "urn:other:scope" + assert VALIDATOR.validate_capture(capture)["status"] == "unverified" + + +def test_opaque_encodings_are_unverified_not_misreported_as_invalid(capture): + columns = [{"name": "opaque", "datatype": "Opaque"}] + resource(capture)["text"] = 'opaque\r\n"{""x"":1}"\r\n' + resource(capture)["_meta"][VALIDATOR.METADATA]["columns"] = columns + payload(capture)["preview"].update(columns=columns, rows=[[{"x": 1}]]) + assert VALIDATOR.validate_capture(capture)["status"] == "unverified" + + +def test_float_preview_cannot_lose_negative_zero(capture): + columns = [{"name": "f", "datatype": "Float"}] + resource(capture)["text"] = "f\r\n-0.0\r\n" + resource(capture)["_meta"][VALIDATOR.METADATA]["columns"] = columns + payload(capture)["preview"].update(columns=columns, rows=[[-0.0]]) + assert VALIDATOR.validate_capture(capture)["status"] == "passed" + payload(capture)["preview"]["rows"] = [[0.0]] + assert "PREVIEW_VALUES" in codes(VALIDATOR.validate_capture(capture)) + + +def test_large_valid_csv_cells_are_unverified_when_parser_budget_is_exceeded(capture): + columns = [{"name": "s", "datatype": "String"}] + resource(capture)["text"] = "s\r\n" + ("x" * 200000) + "\r\n" + resource(capture)["_meta"][VALIDATOR.METADATA]["columns"] = columns + payload(capture).pop("preview") + assert VALIDATOR.validate_capture(capture)["status"] == "unverified" + + +@pytest.mark.parametrize(("text", "quoted_null"), [ + ('s\r\n"\\N"\r\n', True), + ('s\r\n\\N\r\n', False), + ('"\\N"\r\nx\r\n', False), + ('s\r\n"line1\r\n""\\N"""\r\n', False), + ('s\r\n"\\\\N"\r\n', False), +]) +def test_csv_null_quoting_is_checked_without_confusing_headers_or_escaped_quotes(text, quoted_null): + assert VALIDATOR._has_quoted_null(text) == quoted_null + + +@pytest.mark.parametrize("body", ['{"tool":1,"tool":2}', '{"x":NaN}', 'not-json']) +def test_cli_rejects_malformed_capture(tmp_path, capsys, body): + path = tmp_path / "capture.json" + path.write_text(body, encoding="utf-8") + assert VALIDATOR.main([str(path)]) == 1 + assert json.loads(capsys.readouterr().out)["status"] == "failed" + + +def test_cli_exit_codes(capture, tmp_path, capsys): + path = tmp_path / "capture.json" + for expected, mutate in [ + (0, lambda c: None), + (2, lambda c: c["tool"].update(inputSchema={"type": "object"})), + (1, lambda c: success(c).update(isError=True)), + ]: + value = copy.deepcopy(capture) + mutate(value) + path.write_text(json.dumps(value), encoding="utf-8") + assert VALIDATOR.main([str(path)]) == expected + report = json.loads(capsys.readouterr().out) + assert report["status"] == {0: "passed", 1: "failed", 2: "unverified"}[expected] diff --git a/validation/validate_mcp.py b/validation/validate_mcp.py new file mode 100644 index 000000000..9e7658beb --- /dev/null +++ b/validation/validate_mcp.py @@ -0,0 +1,430 @@ +#!/usr/bin/env python3 +# /// script +# requires-python = ">=3.11" +# dependencies = ["jsonschema>=4.26.0"] +# /// +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Check captured MCP tool declarations and results against the Ossie profile.""" + +import argparse +import base64 +import binascii +import csv +import datetime +import io +import json +import math +import re +from collections import Counter +from pathlib import Path + +from jsonschema import Draft202012Validator, FormatChecker +from jsonschema.exceptions import SchemaError +from referencing import Registry, Resource +from referencing.exceptions import NoSuchResource + +SCHEMA_DIR = Path(__file__).with_name("mcp") +VERSION = "0.4-draft" +METADATA = "org.apache.ossie/execute_query" +UNCHECKED = [ + "query expression/name/path/grain semantics and cross-engine answers", + "authorization, read-only enforcement and absence of hidden execution", + "live transport, discovery, Tasks lifecycle and deployment limits", + "Markdown meaning and optional binary file format fidelity", +] + + +def _no_retrieval(uri): + raise NoSuchResource(ref=uri) + + +def _schemas(): + schemas = {} + for path in SCHEMA_DIR.glob("*.schema.json"): + schema = json.loads(path.read_text(encoding="utf-8")) + Draft202012Validator.check_schema(schema) + schemas[schema["$id"]] = schema + registry = Registry(retrieve=_no_retrieval).with_resources( + (uri, Resource.from_contents(schema)) for uri, schema in schemas.items() + ) + return schemas, registry + + +def _pointer(parts): + return "/" + "/".join(str(part).replace("~", "~0").replace("/", "~1") for part in parts) + + +def _canonical(schema): + """Recognize the published contract; do not attempt arbitrary schema equivalence.""" + annotations = {"$schema", "$id", "$comment", "title", "description", "examples", "default", "$defs"} + budget = 50000 + + def visit(node, depth=0, context="schema"): + nonlocal budget + budget -= 1 + if depth > 64 or budget < 0: + raise ValueError("Schema normalization budget exceeded") + if isinstance(node, dict): + if context == "schema" and depth > 0 and "$id" in node: + raise ValueError("Nested reference scopes are not recognized") + if context == "schema" and "$ref" in node: + ref = node["$ref"] + if not isinstance(ref, str) or not ref.startswith("#/"): + raise ValueError("Only local JSON Pointer references are recognized") + target = schema + for part in ref[2:].split("/"): + target = target[part.replace("~1", "/").replace("~0", "~")] + expanded = visit(target, depth + 1) + siblings = visit({key: value for key, value in node.items() if key != "$ref"}, depth + 1) + return {"allOf": [expanded, siblings]} if siblings else expanded + result = {} + for key, value in node.items(): + if context == "schema" and key in annotations: + continue + if context == "schema" and key in {"$dynamicRef", "$recursiveRef"}: + raise ValueError("Dynamic references are not recognized") + child_context = "schema" + if context == "schema" and key in {"properties", "patternProperties", "dependentSchemas"}: + child_context = "mapping" + elif context == "schema" and key in {"const", "enum"}: + child_context = "data" + elif context == "data": + child_context = "data" + normalized = visit(value, depth + 1, child_context) + if context == "schema" and key in {"required", "enum", "allOf", "anyOf", "oneOf"}: + normalized = sorted(normalized, key=lambda item: json.dumps(item, sort_keys=True)) + result[key] = normalized + return result + if isinstance(node, list): + return [visit(item, depth + 1, context) for item in node] + return node + + return visit(schema) + + +def _decode_csv(value): + if value == r"\N": + return None + if value.startswith("\\"): + if not value.startswith("\\\\"): + raise ValueError("Non-null strings beginning with backslash must be escaped") + return value[1:] + return value + + +def _has_quoted_null(text): + # csv.reader discards quoting; the profile's null token must be unquoted. + in_quotes, field_start, body = False, True, False + index = 0 + while index < len(text): + char = text[index] + if in_quotes: + if char == '"': + if text[index:index + 2] == '""': + index += 2 + continue + in_quotes = False + elif char == '"' and field_start: + after = text[index + 4:index + 5] + if body and text[index:index + 4] == r'"\N"' and after in {"", ",", "\r", "\n"}: + return True + in_quotes, field_start = True, False + elif char in {",", "\r", "\n"}: + field_start = True + if char != ",": + body = True + else: + field_start = False + index += 1 + return False + + +def _cell(value, datatype, from_csv=False): + if value is None: + return None + if datatype == "String" or datatype is None or datatype == "Opaque": + if not isinstance(value, str): + raise ValueError("Non-text opaque encodings cannot be verified by this checker") + return value + if datatype in {"Integer", "Decimal"}: + pattern = r"[+-]?\d+" if datatype == "Integer" else r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?" + if not isinstance(value, str) or re.fullmatch(pattern, value, re.ASCII) is None: + raise ValueError(f"{datatype} must be an exact locale-neutral string") + return value + if datatype == "Boolean": + if from_csv and value in {"true", "false"}: + return value == "true" + if not from_csv and isinstance(value, bool): + return value + raise ValueError("Boolean must be a JSON boolean / CSV true or false") + if datatype == "Float": + if from_csv: + if re.fullmatch(r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", value, re.ASCII) is None: + raise ValueError("Float must be locale-neutral numeric text") + value = float(value) + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise ValueError("Float must be a finite JSON number") + return float(value) + if not isinstance(value, str): + raise ValueError(f"{datatype} must be an ISO 8601 string") + if datatype == "Date": + if re.fullmatch(r"\d{4}-\d{2}-\d{2}", value, re.ASCII) is None: + raise ValueError("Date must use YYYY-MM-DD") + datetime.date.fromisoformat(value) + elif datatype == "Time": + parsed = datetime.time.fromisoformat(value) + if parsed.tzinfo is not None: + raise ValueError("Time must be timezone-naive") + else: + if "T" not in value: + raise ValueError("DateTime must include the ISO T separator") + parsed = datetime.datetime.fromisoformat(value) + if (parsed.tzinfo is not None) != (datatype == "DateTimeTz"): + raise ValueError("DateTime and DateTimeTz must preserve timezone distinction") + return value + + +def validate_capture(capture): + """Return evidence about captured contract conformance, never engine certification.""" + schemas, registry = _schemas() + findings, unverified = [], [] + + def issue(code, path, message): + findings.append({"code": code, "path": path, "message": message}) + + def validate(value, schema, path): + errors = list(Draft202012Validator( + schema, registry=registry, format_checker=FormatChecker() + ).iter_errors(value)) + for error in errors: + issue("CONTRACT_SCHEMA", path + _pointer(error.absolute_path), error.message) + return not errors + + def report(count): + return { + "profile": VERSION, + "scope": "captured MCP endpoint contract", + "status": "failed" if findings else ("unverified" if unverified else "passed"), + "cases_checked": count, + "findings": findings, + "unverified": unverified, + "unchecked": UNCHECKED, + } + + def schema_for(name): + return schemas[f"urn:apache:ossie:execute-query:{name}:{VERSION}"] + + if not validate(capture, schema_for("capture"), ""): + return report(0) + tool = capture["tool"] + for key, name in (("inputSchema", "input"), ("outputSchema", "output")): + if key not in tool: + continue + try: + Draft202012Validator.check_schema(tool[key]) + except SchemaError as error: + issue("INVALID_DECLARATION", f"/tool/{key}", error.message) + continue + try: + recognized = _canonical(tool[key]) == _canonical(schema_for(name)) + except (ValueError, KeyError, TypeError, RecursionError) as error: + unverified.append({"path": f"/tool/{key}", "reason": str(error)}) + else: + if not recognized: + unverified.append({ + "path": f"/tool/{key}", + "reason": "Declaration is not recognized as the published schema; equivalence is unproven", + }) + if tool.get("annotations", {}).get("readOnlyHint") is False: + issue("READ_ONLY_DECLARATION", "/tool/annotations/readOnlyHint", "Profile declares read-only execution") + + models = {} + for index, case in enumerate(capture["cases"]): + path = f"/cases/{index}/result" + arguments, result = case["arguments"], case["result"] + payload = result.get("structuredContent") + input_valid = Draft202012Validator(schema_for("input")).is_valid(arguments) + if not input_valid and not result["isError"]: + issue("INVALID_INPUT_ACCEPTED", path, "Arguments outside the contract must not return success") + if payload is None: + if "outputSchema" in tool: + issue("MISSING_STRUCTURED_OUTPUT", path, "Tool advertised outputSchema but returned no structuredContent") + else: + unverified.append({"path": path, "reason": "Markdown-only interpretation requires manual review"}) + continue + if result["isError"] != (payload["status"] == "error"): + issue("STATUS_MISMATCH", path, "isError and structured status disagree") + if "data_source_id" in payload and payload["data_source_id"] != arguments.get("data_source_id"): + issue("SOURCE_MISMATCH", path, "Result source must match supplied source") + if "model" in payload and "data_source_id" in payload: + model, source = payload["model"], payload["data_source_id"] + identity = (model["id"], model["revision"]) + if source in models and models[source] != identity: + issue("MODEL_REBOUND", path + "/model", "One binding returned different model revisions") + models[source] = identity + embedded = {} + for block_index, block in enumerate(result["content"]): + if block["type"] != "resource": + continue + resource = block["resource"] + resource_path = path + f"/content/{block_index}/resource" + uri = resource["uri"] + if uri in embedded: + issue("DUPLICATE_RESOURCE", resource_path, "Embedded resource URIs must be distinct") + embedded[uri] = resource + if "blob" in resource: + try: + base64.b64decode(resource["blob"], validate=True) + except (ValueError, binascii.Error): + issue("INVALID_BASE64", resource_path + "/blob", "Binary resource is not valid base64") + if payload["status"] == "error": + continue + descriptors = payload["result"]["resources"] + descriptor_uris = [descriptor["uri"] for descriptor in descriptors] + if len(set(descriptor_uris)) != len(descriptor_uris): + issue("DUPLICATE_RESOURCE", path + "/structuredContent/result/resources", "Descriptor URIs must be distinct") + if any(resource["mimeType"] == "text/csv" and uri not in descriptor_uris for uri, resource in embedded.items()): + issue("UNDESCRIBED_CSV", path, "Every embedded CSV requires a result descriptor") + for descriptor in descriptors: + resource = embedded.get(descriptor["uri"]) + if resource is None: + issue("MISSING_EMBEDDED_RESOURCE", path, "Resource descriptor has no embedded bytes") + continue + if resource["mimeType"] != descriptor["mime_type"]: + issue("RESOURCE_MISMATCH", path, "Descriptor MIME type differs from embedded resource") + expected_mime = { + "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "parquet": "application/vnd.apache.parquet", + }.get(descriptor["format"]) + if expected_mime is not None and descriptor["mime_type"] != expected_mime: + issue("RESOURCE_MISMATCH", path, "Export format requires its declared standard MIME type") + if descriptor["format"] in {"xlsx", "parquet"} and "blob" not in resource: + issue("BINARY_NOT_BLOB", path, "XLSX/Parquet must use base64 blob content") + if descriptor["format"] != "csv": + continue + if "text" not in resource: + issue("CSV_NOT_TEXT", path, "CSV must be embedded as text") + continue + metadata = resource.get("_meta", {}).get(METADATA) + preview_schema = schema_for("output")["properties"]["preview"] + metadata_schema = { + "type": "object", + "required": ["columns", "row_count", "completeness", "csv_null_value", "csv_escape_prefix"], + "properties": { + "columns": preview_schema["properties"]["columns"], + "row_count": {"type": "integer", "minimum": 0}, + "completeness": {"enum": ["complete", "truncated", "unknown"]}, + "csv_null_value": {"const": r"\N"}, + "csv_escape_prefix": {"const": "\\"}, + }, + } + if not validate(metadata, metadata_schema, path + "/csv_metadata"): + continue + if any(metadata[key] != payload["result"][key] for key in ("row_count", "completeness")): + issue("CSV_METADATA_MISMATCH", path, "CSV counts/completeness differ from the result") + columns = metadata["columns"] + if _has_quoted_null(resource["text"]): + issue("VALUE_ENCODING", path, "CSV null marker must be unquoted; literal backslashes must be escaped") + try: + rows = list(csv.reader(io.StringIO(resource["text"], newline=""), strict=True)) + except csv.Error as error: + if str(error).startswith("field larger than field limit"): + unverified.append({"path": path, "reason": "CSV parser field-size budget exceeded"}) + else: + issue("INVALID_CSV", path, "CSV cannot be parsed") + continue + if not rows or rows[0] != [column["name"] for column in columns]: + issue("CSV_HEADER", path, "CSV header differs from ordered column metadata") + continue + rows = rows[1:] + if len(rows) != payload["result"]["row_count"]: + issue("CSV_ROW_COUNT", path, "CSV row count differs from materialized count") + if any(len(row) != len(columns) for row in rows): + issue("CSV_ARITY", path, "CSV row width differs from column metadata") + continue + preview = payload.get("preview") + try: + values = [ + tuple(_cell(_decode_csv(cell), column.get("datatype"), True) for cell, column in zip(row, columns)) + for row in rows + ] + if preview is None: + continue + if preview["columns"] != columns: + issue("PREVIEW_COLUMNS", path, "Preview and CSV column descriptors differ") + if preview["row_count"] != len(preview["rows"]): + issue("PREVIEW_ROW_COUNT", path, "Preview row_count differs from its rows") + if preview["has_more"] != (payload["result"]["row_count"] > preview["row_count"]): + issue("PREVIEW_COMPLETENESS", path, "Preview has_more differs from materialized count") + if any(len(row) != len(columns) for row in preview["rows"]): + issue("PREVIEW_ARITY", path, "Preview row width differs from column metadata") + continue + displayed = [ + tuple(_cell(cell, column.get("datatype")) for cell, column in zip(row, columns)) + for row in preview["rows"] + ] + value_keys = [json.dumps(row, allow_nan=False) for row in values] + display_keys = [json.dumps(row, allow_nan=False) for row in displayed] + if Counter(display_keys) - Counter(value_keys): + issue("PREVIEW_VALUES", path, "Preview contains values or repetitions absent from CSV") + if preview.get("selection") == "first_rows" and display_keys != value_keys[:len(display_keys)]: + issue("PREVIEW_SELECTION", path, "First-row preview differs from CSV order") + except (ValueError, OverflowError) as error: + if str(error).startswith("Non-text opaque"): + unverified.append({"path": path, "reason": str(error)}) + else: + issue("VALUE_ENCODING", path, str(error)) + return report(len(capture["cases"])) + + +def _unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate JSON key: {key}") + result[key] = value + return result + + +def _reject_constant(value): + raise ValueError(f"Non-finite JSON constant: {value}") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("capture", type=Path, help="Capture JSON; see validation/mcp/example-capture.json") + args = parser.parse_args(argv) + try: + if args.capture.stat().st_size > 16 * 1024 * 1024: + raise ValueError("Capture exceeds the checker's 16 MiB input bound") + capture = json.loads( + args.capture.read_text(encoding="utf-8"), + object_pairs_hook=_unique_object, parse_constant=_reject_constant, + ) + except (OSError, ValueError, RecursionError) as error: + print(json.dumps({"status": "failed", "findings": [{"code": "CAPTURE_INPUT", "message": str(error)}]})) + return 1 + report = validate_capture(capture) + print(json.dumps(report, indent=2, allow_nan=False)) + return {"passed": 0, "failed": 1, "unverified": 2}[report["status"]] + + +if __name__ == "__main__": + raise SystemExit(main())