World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#15274] fix(mcp-server): Classify Gravitino errors, enrich audit logs, and update docs (#15275)
Qi Yue43686fe6a3f
diff --git a/docs/gravitino-mcp-server.md b/docs/gravitino-mcp-server.mdindex 330a3b3954..616f38ea56 100644--- a/docs/gravitino-mcp-server.md+++ b/docs/gravitino-mcp-server.md@@ -69,90 +69,95 @@ You could start Gravitino MCP server by Docker image, `docker run -p 8000:8000 -Gravitino MCP server supports the following tools, and you could export tool by tag.-| Tool name | Description | Tag |-|-------------------------------------|--------------------------------------------------------------------------------|-----------------|-| `list_metalakes` | Retrieve the metalakes the caller can access. | `metalake` |-| `get_list_of_catalogs` | Retrieve a list of all catalogs in the system. | `catalog` |-| `create_catalog` | Create a new catalog. | `catalog` |-| `alter_catalog` | Alter an existing catalog. | `catalog` |-| `drop_catalog` | Drop a catalog. | `catalog` |-| `set_catalog_in_use` | Enable or disable a catalog. | `catalog` |-| `get_list_of_schemas` | Retrieve a list of schemas belonging to a specific catalog. | `schema` |-| `create_schema` | Create a new schema. | `schema` |-| `alter_schema` | Alter an existing schema. | `schema` |-| `drop_schema` | Drop a schema. | `schema` |-| `get_list_of_tables` | Retrieve a list of tables within a specific catalog and schema. | `table` |-| `get_table_metadata_details` | Retrieve comprehensive metadata details for a specific table. | `table` |-| `create_table` | Create a new table. | `table` |-| `alter_table` | Alter an existing table. | `table` |-| `drop_table` | Drop a table. | `table` |-| `list_of_models` | Retrieve a list of models within a specific catalog and schema. | `model` |-| `load_model` | Retrieve comprehensive metadata details for a specific model. | `model` |-| `list_model_versions` | Retrieve a list of versions for a specific model. | `model` |-| `load_model_version` | Retrieve comprehensive metadata details for a specific model version. | `model` |-| `load_model_version_by_alias` | Retrieve comprehensive metadata details for a specific model version by alias. | `model` |-| `register_model` | Register a new model. | `model` |-| `delete_model` | Delete a model. | `model` |-| `link_model_version` | Link a new version to a model. | `model` |-| `delete_model_version` | Delete a model version. | `model` |-| `delete_model_version_by_alias` | Delete a model version by one of its aliases. | `model` |-| `alter_model` | Alter an existing model. | `model` |-| `alter_model_version` | Alter a model version. | `model` |-| `alter_model_version_by_alias` | Alter a model version by one of its aliases. | `model` |-| `metadata_type_to_fullname_formats` | Retrieve the metadata type to fullname formats mapping. | `metadata` |-| `list_of_topics` | Retrieve a list of topics within a specific catalog and schema. | `topic` |-| `load_topic` | Retrieve comprehensive metadata details for a specific topic. | `topic` |-| `create_topic` | Create a new topic. | `topic` |-| `alter_topic` | Alter an existing topic. | `topic` |-| `delete_topic` | Delete a topic. | `topic` |-| `list_of_filesets` | Retrieve a list of filesets within a specific catalog and schema. | `fileset` |-| `load_fileset` | Retrieve comprehensive metadata details for a specific fileset. | `fileset` |-| `list_files_in_fileset` | Retrieve a list of files within a specific fileset. | `fileset` |-| `create_fileset` | Create a new fileset. | `fileset` |-| `alter_fileset` | Alter an existing fileset. | `fileset` |-| `drop_fileset` | Drop a fileset. | `fileset` |-| `list_of_jobs` | Retrieve a list of jobs | `job` |-| `get_job_by_id` | Retrieve a job by its ID. | `job` |-| `list_of_job_templates` | Retrieve a list of job templates. | `job` |-| `get_job_template_by_name` | Retrieve a job template by its name. | `job` |-| `run_job` | Run a job with the specified parameters. | `job` |-| `cancel_job` | Cancel a running job by its ID. | `job` |-| `get_tag_by_name` | Retrieve a tag by its name. | `tag` |-| `list_of_tags` | Retrieve a list of tags. | `tag` |-| `list_tags_for_metadata` | Retrieve a list of tags associated with a specific metadata item. | `tag` |-| `list_metadata_by_tag` | Retrieve a list of metadata items associated with a specific tag. | `tag` |-| `associate_tag_with_metadata` | Associate tags with a specific metadata item. | `tag` |-| `disassociate_tag_from_metadata` | Disassociate tags from a specific metadata item. | `tag` |-| `create_tag` | Create a new tag. | `tag` |-| `alter_tag` | Alter an existing tag. | `tag` |-| `delete_tag` | Delete a tag. | `tag` |-| `list_statistics_for_metadata` | Retrieve a list of statistics associated with a specific metadata item. | `statistics` |-| `list_statistics_for_partition` | Retrieve a list of statistics associated with a specific partition. | `statistics` |-| `get_list_of_policies` | Retrieve a list of policies in the system. | `policy` |-| `get_policy_detail_information` | Retrieve detailed information for a specific policy by policy name. | `policy` |-| `list_policies_for_tag` | List policies directly associated with a tag, including selectors. | `policy`, `tag` |-| `associate_policy_with_tag` | Associate a policy with a tag and selector. | `policy`, `tag` |-| `disassociate_policy_from_tag` | Remove a direct policy association from a tag. | `policy`, `tag` |-| `list_tags_for_policy` | List tags directly associated with a policy, including selectors. | `policy`, `tag` |-| `list_of_partitions` | Retrieve partitions for a table. Only for catalogs with a partition API. | `partition` |-| `get_partition` | Retrieve a partition's metadata. Only for catalogs with a partition API. | `partition` |-| `list_of_views` | Retrieve a list of views for a schema. Only for catalogs supporting views. | `view` |-| `load_view` | Retrieve a view's metadata. Only for catalogs supporting views. | `view` |+| Tool name | Description | Tag |+|-------------------------------------|--------------------------------------------------------------------------------|------------------|+| `list_metalakes` | Retrieve the metalakes the caller can access. | `metalake` |+| `get_list_of_catalogs` | Retrieve a list of all catalogs in the system. | `catalog` |+| `create_catalog` | Create a new catalog. | `catalog` |+| `alter_catalog` | Alter an existing catalog. | `catalog` |+| `drop_catalog` | Drop a catalog. | `catalog` |+| `set_catalog_in_use` | Enable or disable a catalog. | `catalog` |+| `get_list_of_schemas` | Retrieve a list of schemas belonging to a specific catalog. | `schema` |+| `create_schema` | Create a new schema. | `schema` |+| `alter_schema` | Alter an existing schema. | `schema` |+| `drop_schema` | Drop a schema. | `schema` |+| `get_list_of_tables` | Retrieve a list of tables within a specific catalog and schema. | `table` |+| `get_table_metadata_details` | Retrieve comprehensive metadata details for a specific table. | `table` |+| `create_table` | Create a new table. | `table` |+| `alter_table` | Alter an existing table. | `table` |+| `drop_table` | Drop a table. | `table` |+| `list_of_models` | Retrieve a list of models within a specific catalog and schema. | `model` |+| `load_model` | Retrieve comprehensive metadata details for a specific model. | `model` |+| `list_model_versions` | Retrieve a list of versions for a specific model. | `model` |+| `load_model_version` | Retrieve comprehensive metadata details for a specific model version. | `model` |+| `load_model_version_by_alias` | Retrieve comprehensive metadata details for a specific model version by alias. | `model` |+| `register_model` | Register a new model. | `model` |+| `delete_model` | Delete a model. | `model` |+| `link_model_version` | Link a new version to a model. | `model` |+| `delete_model_version` | Delete a model version. | `model` |+| `delete_model_version_by_alias` | Delete a model version by one of its aliases. | `model` |+| `alter_model` | Alter an existing model. | `model` |+| `alter_model_version` | Alter a model version. | `model` |+| `alter_model_version_by_alias` | Alter a model version by one of its aliases. | `model` |+| `metadata_type_to_fullname_formats` | Retrieve the metadata type to fullname formats mapping. | `policy`, `tag` |+| `list_of_topics` | Retrieve a list of topics within a specific catalog and schema. | `topic` |+| `load_topic` | Retrieve comprehensive metadata details for a specific topic. | `topic` |+| `create_topic` | Create a new topic. | `topic` |+| `alter_topic` | Alter an existing topic. | `topic` |+| `delete_topic` | Delete a topic. | `topic` |+| `list_of_filesets` | Retrieve a list of filesets within a specific catalog and schema. | `fileset` |+| `load_fileset` | Retrieve comprehensive metadata details for a specific fileset. | `fileset` |+| `list_files_in_fileset` | Retrieve a list of files within a specific fileset. | `fileset` |+| `create_fileset` | Create a new fileset. | `fileset` |+| `alter_fileset` | Alter an existing fileset. | `fileset` |+| `drop_fileset` | Drop a fileset. | `fileset` |+| `list_of_jobs` | Retrieve a list of jobs | `job` |+| `get_job_by_id` | Retrieve a job by its ID. | `job` |+| `list_of_job_templates` | Retrieve a list of job templates. | `job` |+| `get_job_template_by_name` | Retrieve a job template by its name. | `job` |+| `run_job` | Run a job with the specified parameters. | `job` |+| `cancel_job` | Cancel a running job by its ID. | `job` |+| `get_tag_by_name` | Retrieve a tag by its name. | `tag` |+| `list_of_tags` | Retrieve a list of tags. | `tag` |+| `list_tags_for_metadata` | Retrieve a list of tags associated with a specific metadata item. | `tag` |+| `list_metadata_by_tag` | Retrieve a list of metadata items associated with a specific tag. | `tag` |+| `associate_tag_with_metadata` | Associate tags with a specific metadata item. | `tag` |+| `disassociate_tag_from_metadata` | Disassociate tags from a specific metadata item. | `tag` |+| `create_tag` | Create a new tag. | `tag` |+| `alter_tag` | Alter an existing tag. | `tag` |+| `delete_tag` | Delete a tag. | `tag` |+| `list_statistics_for_metadata` | Retrieve a list of statistics associated with a specific metadata item. | `statistic` |+| `list_statistics_for_partition` | Retrieve a list of statistics associated with a specific partition. | `statistic` |+| `get_list_of_policies` | Retrieve a list of policies in the system. | `policy` |+| `get_policy_detail_information` | Retrieve detailed information for a specific policy by policy name. | `policy` |+| `list_policies_for_tag` | List policies directly associated with a tag, including selectors. | `policy`, `tag` |+| `associate_policy_with_tag` | Associate a policy with a tag and selector. | `policy`, `tag` |+| `disassociate_policy_from_tag` | Remove a direct policy association from a tag. | `policy`, `tag` |+| `list_tags_for_policy` | List tags directly associated with a policy, including selectors. | `policy`, `tag` |+| `list_of_partitions` | Retrieve partitions for a table. Only for catalogs with a partition API. | `partition` |+| `get_partition` | Retrieve a partition's metadata. Only for catalogs with a partition API. | `partition` |+| `list_of_views` | Retrieve a list of views for a schema. Only for catalogs supporting views. | `view` |+| `load_view` | Retrieve a view's metadata. Only for catalogs supporting views. | `view` || `list_of_semantic_models` | List the Semantic Models the caller can access in a schema. | `semantic_model` |-| `list_metrics` | List visible metric identifiers across Semantic Models in a schema. | `semantic_model` |-| `list_metric_infos` | List complete visible metrics across Semantic Models in a schema. | `semantic_model` |+| `list_metrics` | List visible metric identifiers across Semantic Models in a schema. | `semantic_model` |+| `list_metric_infos` | List complete visible metrics across Semantic Models in a schema. | `semantic_model` || `list_semantic_model_datasets` | List visible datasets directly associated with a source table or view. | `semantic_model` || `load_semantic_model` | Load a Semantic Model's metadata and definition. | `semantic_model` || `create_semantic_model` | Create a Semantic Model from a native REST definition. | `semantic_model` |-| `alter_semantic_model` | Apply Semantic Model updates atomically. | `semantic_model` |-| `drop_semantic_model` | Drop a Semantic Model's metadata. | `semantic_model` |+| `alter_semantic_model` | Apply Semantic Model updates atomically. | `semantic_model` |+| `drop_semantic_model` | Drop a Semantic Model's metadata. | `semantic_model` |+| `list_of_domains` | Retrieve a list of domains the caller can access. | `domain` |+| `get_domain_by_name` | Retrieve a complete domain snapshot by name. | `domain` |+| `list_subdomains` | Retrieve immediate subdomains of a domain. | `domain` |+| `list_domain_members` | List directly tagged or expanded effective members of a domain. | `domain` |+| `list_domains_for_metadata` | List domains associated with a metadata leaf object. | `domain` |### Semantic ModelsSemantic Model tools manage semantic metadata and discover source associations through the Gravitino REST API.For concepts and source requirements, see [Semantic Models](./semantic-models.md). For governanceand Ossie import/export, see [Manage Semantic Model Metadata](./manage-semantic-model-metadata-using-gravitino.md).-Use the `semantic_model` tag with `--include-tool-tags` to expose these tools.+These tools are exposed by default and carry the `semantic_model` tag; include `semantic_model` in `--include-tool-tags` when restricting the server to a tag allowlist.They use the same per-call `metalake` selection and authentication as other tools;Gravitino filters listings by visibility and checks source-table access when creating orreplacing definitions.@@ -245,16 +250,16 @@ indicating whether it was dropped. It removes semantic metadata without deletingSee [Domains](./domains.md) for membership semantics and the[Domain guide](./manage-domains-in-gravitino.md) for SDK and REST mutations.-Use `--include-tool-tags domain` to expose the five Domain tools.+These five Domain tools are exposed by default and carry the `domain` tag; include `domain` in `--include-tool-tags` when restricting the server to a tag allowlist.All are annotated as read-only and idempotent and issue only GET requests.-| Tool | Arguments | Result |-|------|-----------|--------|-| `list_of_domains` | `details=true` | Domain snapshots, or names when false |-| `get_domain_by_name` | `domain_name` | A complete domain snapshot |-| `list_subdomains` | `domain_name`, `details=true` | Immediate subdomain snapshots or names |-| `list_domain_members` | `domain_name`, optional `types`, `domains`, `name_contains`, `expand` | Directly tagged objects, including catalogs and schemas. Use `expand=true` for accessible recorded leaves whose effective tags match |-| `list_domains_for_metadata` | `metadata_type`, `metadata_full_name`, `details=true` | Domains of a leaf object, including all relations when details is true |+| Tool | Arguments | Result |+|-----------------------------|-----------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------|+| `list_of_domains` | `details=true` | Domain snapshots, or names when false |+| `get_domain_by_name` | `domain_name` | A complete domain snapshot |+| `list_subdomains` | `domain_name`, `details=true` | Immediate subdomain snapshots or names |+| `list_domain_members` | `domain_name`, optional `types`, `domains`, `name_contains`, `expand` | Directly tagged objects, including catalogs and schemas. Use `expand=true` for accessible recorded leaves whose effective tags match |+| `list_domains_for_metadata` | `metadata_type`, `metadata_full_name`, `details=true` | Domains of a leaf object, including all relations when details is true |Results follow the existing MCP JSON-string convention; empty lists return `[]`.Snapshots retain the server's backing tag, status, parent, properties, audit and@@ -296,21 +301,22 @@ binding changes are exposed. Existing tools in other groups retain their behavioYou could config Gravitino MCP server by arguments, `uv run mcp_server -h` shows the detailed information.-| Argument | Description | Default value | Required |-| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------- | -------- |-| `--metalake` | Default metalake, used by any tool call that does not name one. See Selecting a metalake. | none | No |-| `--gravitino-uri` | The URI of Gravitino server. | `http://127.0.0.1:8090` | No |-| `--gravitino-read-timeout` | Gravitino response read timeout in seconds; or set `GRAVITINO_READ_TIMEOUT`. Must be finite and positive. Connect, write and pool timeouts remain 5 seconds. | `60` | No |-| `--transport` | Transport protocol: stdio (local), http / streamable-http (Streamable HTTP). | `stdio` | No |-| `--mcp-url` | The URL of MCP server if using HTTP transport. | `http://127.0.0.1:8000/mcp` | No |-| `--token` | Static credential for Gravitino; or set `GRAVITINO_TOKEN`. See Authentication. Wins over OAuth client-credentials. | none (anonymous) | No |-| `--oauth-token-endpoint` | OAuth2 token URL for client-credentials. Or `GRAVITINO_OAUTH_TOKEN_ENDPOINT`. | none | No |-| `--oauth-client-id` | OAuth2 client id. Or `GRAVITINO_OAUTH_CLIENT_ID`. | none | No |-| `--oauth-client-secret` | OAuth2 client secret. Or `GRAVITINO_OAUTH_CLIENT_SECRET`. | none | No |-| `--oauth-scope` | Optional OAuth2 scope. Or `GRAVITINO_OAUTH_SCOPE`. | none | No |-| `--no-service-identity-fallback` | HTTP only: reject requests with no `Authorization` when OAuth or `--token` is set. Or `GRAVITINO_NO_SERVICE_IDENTITY_FALLBACK`. | `false` | No |-| `--tls-cert` | PEM certificate to serve the endpoint over HTTPS. Requires `--tls-key`. | none | No |-| `--tls-key` | PEM private key to serve the endpoint over HTTPS. Requires `--tls-cert`. | none | No |+| Argument | Description | Default value | Required |+|----------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------|----------|+| `--metalake` | Default metalake, used by any tool call that does not name one. See Selecting a metalake. | none | No |+| `--gravitino-uri` | The URI of Gravitino server. | `http://127.0.0.1:8090` | No |+| `--gravitino-read-timeout` | Gravitino response read timeout in seconds; or set `GRAVITINO_READ_TIMEOUT`. Must be finite and positive. Connect, write and pool timeouts remain 5 seconds. | `60` | No |+| `--include-tool-tags` | Comma-separated allowlist of object-type tags from the Supported Tools table (`catalog`, `domain`, `fileset`, `job`, `metalake`, `model`, `partition`, `policy`, `schema`, `semantic_model`, `statistic`, `table`, `tag`, `topic`, `view`). Filters by object type, so it cannot produce a read-only tool set. | empty (all tools) | No |+| `--transport` | Transport protocol: stdio (local), http / streamable-http (Streamable HTTP). | `stdio` | No |+| `--mcp-url` | The URL of MCP server if using HTTP transport. | `http://127.0.0.1:8000/mcp` | No |+| `--token` | Static credential for Gravitino; or set `GRAVITINO_TOKEN`. See Authentication. Wins over OAuth client-credentials. | none (anonymous) | No |+| `--oauth-token-endpoint` | OAuth2 token URL for client-credentials. Or `GRAVITINO_OAUTH_TOKEN_ENDPOINT`. | none | No |+| `--oauth-client-id` | OAuth2 client id. Or `GRAVITINO_OAUTH_CLIENT_ID`. | none | No |+| `--oauth-client-secret` | OAuth2 client secret. Or `GRAVITINO_OAUTH_CLIENT_SECRET`. | none | No |+| `--oauth-scope` | Optional OAuth2 scope. Or `GRAVITINO_OAUTH_SCOPE`. | none | No |+| `--no-service-identity-fallback` | HTTP only: reject requests with no `Authorization` when OAuth or `--token` is set. Or `GRAVITINO_NO_SERVICE_IDENTITY_FALLBACK`. | `false` | No |+| `--tls-cert` | PEM certificate to serve the endpoint over HTTPS. Requires `--tls-key`. | none | No |+| `--tls-key` | PEM private key to serve the endpoint over HTTPS. Requires `--tls-cert`. | none | No |A response read timeout means the MCP server stopped waiting for Gravitino. The operation may still complete on the server. Check the result before retrying, especially for writes. This timeout bounds waiting for response data, not the total duration of the server operation.@@ -324,13 +330,13 @@ Pass `--token` (or set the `GRAVITINO_TOKEN` environment variable) to authenticaA bare value is treated as an OAuth2 token and sent as `Authorization: Bearer <token>`. A value that already begins with an HTTP authentication scheme is forwarded with that scheme preserved, so the credential can match whatever `gravitino.authenticators` the server is configured with:-| `--token` value | `Authorization` header sent |-|-----------------------------|--------------------------------|-| `abc` | `Bearer abc` |-| `Bearer abc` | `Bearer abc` |-| `Basic dXNlcjpwYXNz` | `Basic dXNlcjpwYXNz` |-| `Custom credentials` | `Custom credentials` |-| empty or whitespace only | none (anonymous) |+| `--token` value | `Authorization` header sent |+|--------------------------|-----------------------------|+| `abc` | `Bearer abc` |+| `Bearer abc` | `Bearer abc` |+| `Basic dXNlcjpwYXNz` | `Basic dXNlcjpwYXNz` |+| `Custom credentials` | `Custom credentials` |+| empty or whitespace only | none (anonymous) |The built-in scheme names (`Basic`, `Bearer`, `Negotiate`) are recognized case-insensitively and normalized to the capitalization Gravitino's authenticators expect; a custom scheme name is forwarded unchanged.@@ -454,22 +460,45 @@ No default at all, every call chooses:uv run mcp_server --transport http --mcp-url http://0.0.0.0:8000/mcp```+## Tool errors++A tool execution failure handled by the Gravitino middleware returns a `CallToolResult` with `isError: true`. Its text+includes the error prefix and message. Clients can read the numeric classification+code and category from `_meta["org.apache.gravitino/error"]`. For example, a+Gravitino HTTP 409 returns `{"code": -32009, "category": "conflict"}` there.+Gravitino HTTP 401 and 403 both use code `-32000` and have the respective+categories `unauthorized` and `permission_denied`. An upstream HTTP 429 has the+category `rate_limited`.+If the configured OAuth token endpoint rejects the MCP server's credentials or+cannot be found, the tool reports `internal_error`. Check the server's OAuth+configuration.++MCP protocol errors use the usual JSON-RPC error envelope. If strict SDK input+validation rejects a request before middleware runs, the SDK supplies the error+text and the call has no Gravitino classification metadata or tool audit record.+## Audit Logging-Every tool invocation is recorded as one structured JSON line in `gravitino-mcp-audit.log` (written to the server's working directory). Each record is attributed to the incoming HTTP `Authorization` header when present; otherwise to the configured service identity (`--token` or OAuth client id).+Every tool invocation that reaches the audit middleware is recorded as one structured JSON line in `gravitino-mcp-audit.log` (written to the server's working directory). Each record is attributed to the incoming HTTP `Authorization` header when present; otherwise to the configured service identity (`--token` or OAuth client id).-| Field | Description |-|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-| `timestamp` | UTC ISO-8601 time of the call. |-| `principal` | Caller identity: username for `Basic` simple auth, `bearer:<first-16-hex-of-sha256-of-token>` for a Bearer token (a fingerprint of the token, so it changes when the token is refreshed), `oauth:<first-16-hex-of-sha256-of-client-id>` when OAuth client-credentials is the service identity (stdio or HTTP with no caller header), or `anonymous` when no identity is present. |-| `tool` | Name of the invoked MCP tool. |-| `outcome` | `allow` for successful calls, `deny` for failed ones. `deny` is emitted for any tool-call exception (authorization denial being the common case); inspect `error_type` to disambiguate. |-| `error_type` | Exception class name, present only when `outcome` is `deny`. |+| Field | Description |+|------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|+| `timestamp` | UTC ISO-8601 time of the call. |+| `principal` | Caller identity: username for `Basic` simple auth, `bearer:<first-16-hex-of-sha256-of-token>` for a Bearer token (a fingerprint of the token, so it changes when the token is refreshed), `oauth:<first-16-hex-of-sha256-of-client-id>` when OAuth client-credentials is the service identity (stdio or HTTP with no caller header), or `anonymous` when no identity is present. |+| `tool` | Name of the invoked MCP tool. |+| `outcome` | `allow` for successful calls, `deny` for authentication or authorization denials (Gravitino HTTP 401/403, `PermissionError`, or `--no-service-identity-fallback` rejection), and `error` for other failures. |+| `metalake` | Resolved metalake from the per-call argument or the `--metalake` default. Omitted when resolution fails or the tool spans tenants, as `list_metalakes` does. |+| `target_type` | Metadata object type for writes and deletes (for example `schema` or `table`). Omitted for read-only calls and when the full target cannot be determined. |+| `target_name` | Target object full name for write and delete tools (for example `authz.mcpcat.alice_s`); omitted when `target_type` is omitted. |+| `error_type` | Original Gravitino error type (for example `ForbiddenException`, `NoSuchTableException`, `CatalogInUseException`) or exception class name (for example `ConnectError`, `ValueError`, `ReadTimeout`); present only when `outcome` is `deny` or `error`. |+| `error_category` | Normalized failure category (`unauthorized`, `permission_denied`, `invalid_params`, `not_found`, `conflict`, `timeout`, `rate_limited`, `unavailable`, `internal_error`); present only when `outcome` is `deny` or `error`. |For every scheme other than `Basic`, `principal` is a fingerprint of one credential, not a stable user identity. The hash has no key, so the fingerprint suits high-entropy tokens only: a short static credential can be recovered from the log by guessing. To trace what one user did, use the Gravitino server's [audit log](./gravitino-server-config.md#audit-logging).-Example record:+Example records:```json-{"timestamp": "2026-06-16T03:21:09.123456+00:00", "principal": "alice", "tool": "get_list_of_catalogs", "outcome": "allow"}+{"timestamp": "2026-06-16T03:21:09.123456+00:00", "principal": "alice", "tool": "drop_schema", "outcome": "allow", "metalake": "authz", "target_type": "schema", "target_name": "authz.mcpcat.alice_s"}+{"timestamp": "2026-06-16T03:21:10.123456+00:00", "principal": "alice", "tool": "drop_table", "outcome": "deny", "metalake": "authz", "target_type": "table", "target_name": "authz.mcpcat.alice_s.orders", "error_type": "ForbiddenException", "error_category": "permission_denied"}+{"timestamp": "2026-06-16T03:21:11.123456+00:00", "principal": "admin", "tool": "drop_catalog", "outcome": "error", "metalake": "authz", "target_type": "catalog", "target_name": "authz.mcpcat", "error_type": "CatalogInUseException", "error_category": "conflict"}```diff --git a/mcp-server/dev/INSPECTOR_DEMO.md b/mcp-server/dev/INSPECTOR_DEMO.mdindex d3a86f9b46..36f9355bde 100644--- a/mcp-server/dev/INSPECTOR_DEMO.md+++ b/mcp-server/dev/INSPECTOR_DEMO.md@@ -96,20 +96,20 @@ for local convenience.)### Connect-| Field | Value |-|----------------|------------------------------------------|-| Transport Type | `Streamable HTTP` |-| URL | `http://127.0.0.1:8000/mcp` |-| Header Name | `Authorization` |+| Field | Value |+|----------------|---------------------------------------------|+| Transport Type | `Streamable HTTP` |+| URL | `http://127.0.0.1:8000/mcp` |+| Header Name | `Authorization` || Header Value | `Basic YWRtaW46ZHVtbXk=` (this is `admin`) |The two principal tokens (these are Gravitino simple-auth headers, i.e.`Basic base64("<user>:dummy")`):-| Principal | Authorization header value |-|-----------|--------------------------------|-| `admin` | `Basic YWRtaW46ZHVtbXk=` |-| `bob` | `Basic Ym9iOmR1bW15` |+| Principal | Authorization header value |+|-----------|----------------------------|+| `admin` | `Basic YWRtaW46ZHVtbXk=` |+| `bob` | `Basic Ym9iOmR1bW15` |Click **Connect**, then **List Tools** — you should see the full read + writetool surface (catalogs, schemas, tables, filesets, topics, models, tags, …).@@ -160,9 +160,9 @@ Look at the audit log you've been tailing. You should see discrete, correctlyattributed records, for example:```json-{"timestamp": "...", "principal": "admin", "tool": "get_list_of_catalogs", "outcome": "allow"}-{"timestamp": "...", "principal": "bob", "tool": "get_list_of_catalogs", "outcome": "allow"}-{"timestamp": "...", "principal": "bob", "tool": "create_tag", "outcome": "deny", "error_type": "McpError"}+{"timestamp": "...", "principal": "admin", "tool": "get_list_of_catalogs", "outcome": "allow", "metalake": "mcp_authz_it"}+{"timestamp": "...", "principal": "bob", "tool": "get_list_of_catalogs", "outcome": "allow", "metalake": "mcp_authz_it"}+{"timestamp": "...", "principal": "bob", "tool": "create_tag", "outcome": "deny", "metalake": "mcp_authz_it", "target_type": "tag", "target_name": "mcp_authz_it.test_tag", "error_type": "ForbiddenException", "error_category": "permission_denied"}````admin`'s reads attributed to `admin`, `bob`'s reads to `bob`, and `bob`'s denieddiff --git a/mcp-server/mcp_server/client/plain/exception.py b/mcp-server/mcp_server/client/plain/exception.pyindex 25b085778a..0ec333ab42 100644--- a/mcp-server/mcp_server/client/plain/exception.py+++ b/mcp-server/mcp_server/client/plain/exception.py@@ -16,7 +16,21 @@# under the License.+from typing import Optional++class GravitinoException(Exception):"""Custom exception for Gravitino-related errors."""- pass+ def __init__(+ self,+ message: str,+ *,+ status_code: Optional[int] = None,+ error_code: Optional[int] = None,+ error_type: str = "",+ ):+ super().__init__(message)+ self.status_code = status_code+ self.error_code = error_code+ self.error_type = error_typediff --git a/mcp-server/mcp_server/client/plain/plain_rest_client_job_operation.py b/mcp-server/mcp_server/client/plain/plain_rest_client_job_operation.pyindex ddc35b9344..b4c0e0b8ca 100644--- a/mcp-server/mcp_server/client/plain/plain_rest_client_job_operation.py+++ b/mcp-server/mcp_server/client/plain/plain_rest_client_job_operation.py@@ -18,7 +18,6 @@from httpx import AsyncClientfrom mcp_server.client.job_operation import JobOperation-from mcp_server.client.plain.exception import GravitinoExceptionfrom mcp_server.client.plain.utils import (encode_path_segment,extract_content_from_response,@@ -73,9 +72,4 @@ class PlainRESTClientJobOperation(JobOperation):response = await self.rest_client.post(f"/api/metalakes/{encode_path_segment(self.metalake_name)}/jobs/runs/{encode_path_segment(job_id)}")- if response.status_code != 200:- raise GravitinoException(- f"Failed to cancel job {job_id}: {response.text}"- )-return extract_content_from_response(response, "job", {})diff --git a/mcp-server/mcp_server/client/plain/plain_rest_client_operation.py b/mcp-server/mcp_server/client/plain/plain_rest_client_operation.pyindex 69c5279e6f..1cb31cdcd4 100644--- a/mcp-server/mcp_server/client/plain/plain_rest_client_operation.py+++ b/mcp-server/mcp_server/client/plain/plain_rest_client_operation.py@@ -101,7 +101,8 @@ class _GravitinoAsyncClient(httpx.AsyncClient):f"The MCP server stopped waiting for Gravitino ({request.method} "f"{resource}) after a response read "f"timeout of {self.timeout.read:g} seconds. The operation may still "- "complete on the server; check its result before retrying."+ "complete on the server; check its result before retrying.",+ error_type="ReadTimeout",) from excdiff --git a/mcp-server/mcp_server/client/plain/utils.py b/mcp-server/mcp_server/client/plain/utils.pyindex d65601e609..333660d299 100644--- a/mcp-server/mcp_server/client/plain/utils.py+++ b/mcp-server/mcp_server/client/plain/utils.py@@ -17,6 +17,7 @@import loggingfrom decimal import Decimal+from typing import Optionalfrom urllib.parse import quoteimport simplejson@@ -52,7 +53,7 @@ def extract_list_from_response(response, field: str) -> str:"Invalid Gravitino response: invalid JSON") from excif isinstance(payload, dict):- _handle_gravitino_exception(payload)+ _handle_gravitino_exception(payload, status_code=response.status_code)response.raise_for_status()if not isinstance(payload, dict) or "code" not in payload:raise GravitinoException("Invalid Gravitino response: missing code")@@ -71,22 +72,31 @@ def extract_response(response) -> str:def _response_content(response):try:content = response.json(parse_float=Decimal)- except ValueError:+ except ValueError as exc:response.raise_for_status()- raise+ raise GravitinoException(+ "Invalid Gravitino response: invalid JSON"+ ) from excif isinstance(content, dict):- _handle_gravitino_exception(content)+ _handle_gravitino_exception(content, status_code=response.status_code)if not response.is_success:response.raise_for_status()return content-def _handle_gravitino_exception(response: dict):+def _handle_gravitino_exception(+ response: dict, status_code: Optional[int] = None+):error_code = response.get("code", 0)if error_code != 0:t = response.get("type", "")message = response.get("message", "")error_message = f"Error code: {error_code}, Error type: {t}, Error message: {message}"logging.warning(error_message)- raise GravitinoException(error_message)+ raise GravitinoException(+ error_message,+ status_code=status_code,+ error_code=error_code if isinstance(error_code, int) else None,+ error_type=str(t) if t is not None else "",+ )diff --git a/mcp-server/mcp_server/core/audit.py b/mcp-server/mcp_server/core/audit.pyindex e5d06155f4..44598ee844 100644--- a/mcp-server/mcp_server/core/audit.py+++ b/mcp-server/mcp_server/core/audit.py@@ -20,9 +20,173 @@ import binasciiimport hashlibimport jsonimport logging+from dataclasses import dataclassfrom datetime import datetime, timezone+from typing import Any++from pydantic import TypeAdapter_audit_logger = logging.getLogger("gravitino.mcp.audit")+_VERSION = TypeAdapter(int)+++@dataclass(frozen=True)+class _WriteTargetSpec:+ """Describes how to extract a target object's type and name from tool args."""++ target_type: str+ name_fields: tuple[str, ...]+ include_metalake: bool = True+ type_field: str = ""+++# Every mutating (write / delete / action) MCP tool and how to derive the+# target metadata object from its arguments for audit records.+WRITE_TARGET_SPECS: dict[str, _WriteTargetSpec] = {+ # Catalogs+ "create_catalog": _WriteTargetSpec("catalog", ("name",)),+ "alter_catalog": _WriteTargetSpec("catalog", ("catalog_name",)),+ "drop_catalog": _WriteTargetSpec("catalog", ("catalog_name",)),+ "set_catalog_in_use": _WriteTargetSpec("catalog", ("catalog_name",)),+ # Schemas+ "create_schema": _WriteTargetSpec("schema", ("catalog_name", "name")),+ "alter_schema": _WriteTargetSpec("schema", ("catalog_name", "schema_name")),+ "drop_schema": _WriteTargetSpec("schema", ("catalog_name", "schema_name")),+ # Tables+ "create_table": _WriteTargetSpec(+ "table", ("catalog_name", "schema_name", "name")+ ),+ "alter_table": _WriteTargetSpec(+ "table", ("catalog_name", "schema_name", "table_name")+ ),+ "drop_table": _WriteTargetSpec(+ "table", ("catalog_name", "schema_name", "table_name")+ ),+ # Filesets+ "create_fileset": _WriteTargetSpec(+ "fileset", ("catalog_name", "schema_name", "name")+ ),+ "alter_fileset": _WriteTargetSpec(+ "fileset", ("catalog_name", "schema_name", "fileset_name")+ ),+ "drop_fileset": _WriteTargetSpec(+ "fileset", ("catalog_name", "schema_name", "fileset_name")+ ),+ # Topics+ "create_topic": _WriteTargetSpec(+ "topic", ("catalog_name", "schema_name", "name")+ ),+ "alter_topic": _WriteTargetSpec(+ "topic", ("catalog_name", "schema_name", "topic_name")+ ),+ "delete_topic": _WriteTargetSpec(+ "topic", ("catalog_name", "schema_name", "topic_name")+ ),+ # Models and model versions+ "register_model": _WriteTargetSpec(+ "model", ("catalog_name", "schema_name", "name")+ ),+ "alter_model": _WriteTargetSpec(+ "model", ("catalog_name", "schema_name", "model_name")+ ),+ "delete_model": _WriteTargetSpec(+ "model", ("catalog_name", "schema_name", "model_name")+ ),+ # The server assigns the version number after the call. The request names its parent.+ "link_model_version": _WriteTargetSpec(+ "model", ("catalog_name", "schema_name", "model_name")+ ),+ "alter_model_version": _WriteTargetSpec(+ "model_version",+ ("catalog_name", "schema_name", "model_name", "version"),+ ),+ "delete_model_version": _WriteTargetSpec(+ "model_version",+ ("catalog_name", "schema_name", "model_name", "version"),+ ),+ "alter_model_version_by_alias": _WriteTargetSpec(+ "model_version",+ ("catalog_name", "schema_name", "model_name", "alias"),+ ),+ "delete_model_version_by_alias": _WriteTargetSpec(+ "model_version",+ ("catalog_name", "schema_name", "model_name", "alias"),+ ),+ # Semantic models+ "create_semantic_model": _WriteTargetSpec(+ "semantic_model", ("catalog_name", "schema_name", "name")+ ),+ "alter_semantic_model": _WriteTargetSpec(+ "semantic_model",+ ("catalog_name", "schema_name", "semantic_model_name"),+ ),+ "drop_semantic_model": _WriteTargetSpec(+ "semantic_model",+ ("catalog_name", "schema_name", "semantic_model_name"),+ ),+ # Tags and tag associations+ "create_tag": _WriteTargetSpec("tag", ("name",)),+ "alter_tag": _WriteTargetSpec("tag", ("name",)),+ "delete_tag": _WriteTargetSpec("tag", ("name",)),+ "associate_tag_with_metadata": _WriteTargetSpec(+ "", ("metadata_full_name",), type_field="metadata_type"+ ),+ "disassociate_tag_from_metadata": _WriteTargetSpec(+ "", ("metadata_full_name",), type_field="metadata_type"+ ),+ # Policies on tags+ "associate_policy_with_tag": _WriteTargetSpec("tag", ("tag_name",)),+ "disassociate_policy_from_tag": _WriteTargetSpec("tag", ("tag_name",)),+ # Jobs+ "run_job": _WriteTargetSpec("job_template", ("job_template_name",)),+ "cancel_job": _WriteTargetSpec("job", ("job_id",), include_metalake=False),+}+++def _format_target_part(field: str, value: Any) -> str:+ if field == "version":+ # FastMCP validates this argument as an int before constructing the REST path.+ try:+ return str(_VERSION.validate_python(value))+ except ValueError:+ return ""+ return value if isinstance(value, str) else ""+++def extract_write_target(+ tool: str, arguments: Any, metalake: str = ""+) -> tuple[str, str]:+ """Extract ``(target_type, target_name)`` for write/delete MCP tools.++ Never raises: runs on both success and failure audit paths, including when+ a call failed validation because arguments were missing or malformed.+ Returns ``("", "")`` for read-only tools or when required target fields are+ absent or invalid, including an unresolved tenant for a scoped target.+ """+ spec = WRITE_TARGET_SPECS.get(tool)+ if spec is None or not isinstance(arguments, dict):+ return "", ""++ if spec.type_field:+ raw_type = arguments.get(spec.type_field)+ if not isinstance(raw_type, str) or not raw_type.strip():+ return "", ""+ target_type = raw_type.strip().lower()+ else:+ target_type = spec.target_type++ parts: list[str] = []+ for field in spec.name_fields:+ part = _format_target_part(field, arguments.get(field))+ if not part:+ return "", ""+ parts.append(part)++ if spec.include_metalake and target_type != "metalake":+ if not metalake:+ return "", ""+ parts.insert(0, metalake)+ return target_type, ".".join(parts)def _extract_principal(authorization: str) -> str:@@ -65,25 +229,37 @@ def emit(tool: str,outcome: str,error_type: str = "",+ error_category: str = "",metalake: str = "",+ target_type: str = "",+ target_name: str = "",) -> None:"""Write one structured JSON audit record to the audit logger.Args:principal: Identity derived from the request (e.g. "bearer:f39dac6cbaba535e" or "anonymous").tool: MCP tool name that was invoked.- outcome: "allow" for successful calls, "deny" for failed calls. Note the- AuditMiddleware emits "deny" for any tool-call exception (an- authorization denial being the common case), not only- authorization failures; inspect error_type to disambiguate.- error_type: Exception class name when outcome is "deny", empty otherwise.+ outcome: "allow" for successful calls, "deny" for authentication or+ authorization denials (Gravitino 401/403, PermissionError, or+ --no-service-identity-fallback rejection), and "error" for+ all other failures.+ error_type: Original Gravitino error type (e.g. "ForbiddenException",+ "NoSuchTableException") or exception class name (e.g.+ "ConnectError", "ValueError") when outcome is "deny" or+ "error"; empty on "allow".+ error_category: Normalized failure category ("unauthorized",+ "permission_denied", "invalid_params", "not_found",+ "conflict", "timeout", "rate_limited", "unavailable", "internal_error")+ when outcome is "deny" or "error"; empty on "allow".metalake: Metalake the call operated on, resolved - so a call thatrelied on the server default records that default. Empty- only for tools that are not metalake-scoped, such as the- metalake listing, which spans every tenant the caller can- see. Recorded because one server can now serve several- metalakes, so "which tenant did this touch" is no longer- answerable from the server config alone.+ when the tenant could not be resolved or when the tool+ spans tenants, such as the metalake listing.+ target_type: Metadata object type for write/delete tools (e.g.+ "table", "schema", "catalog"); empty for read-only tools+ and unresolved targets.+ target_name: Target object full name for write/delete tools (e.g.+ "authz.mcpcat.alice_s"); empty when target_type is empty."""record = {"timestamp": datetime.now(timezone.utc).isoformat(),@@ -93,7 +269,13 @@ def emit(}if metalake:record["metalake"] = metalake+ if target_type:+ record["target_type"] = target_type+ if target_name:+ record["target_name"] = target_nameif error_type:record["error_type"] = error_type+ if error_category:+ record["error_category"] = error_category_audit_logger.info(json.dumps(record))diff --git a/mcp-server/mcp_server/core/context.py b/mcp-server/mcp_server/core/context.pyindex 8620bd00e8..83f2b43bb2 100644--- a/mcp-server/mcp_server/core/context.py+++ b/mcp-server/mcp_server/core/context.py@@ -165,14 +165,18 @@ def reset_request_metalake(token) -> None:_REQUEST_METALAKE.reset(token)-def get_request_metalake() -> str:- """The metalake this call named, or "" when it named none or named it badly.+def get_request_metalake(default: str = "") -> str:+ """Resolve the requested metalake, returning an empty string for invalid input.- Never raises: audit logging calls this on the failure path too, where the- value may be exactly the malformed input that caused the failure.+ Omitted, null, and blank arguments select the configured default. Audit+ logging also calls this after validation fails, before a tenant is selected."""metalake = _REQUEST_METALAKE.get()- return metalake.strip() if isinstance(metalake, str) else ""+ if metalake is MISSING_METALAKE or metalake is None:+ return default+ if isinstance(metalake, str):+ return metalake.strip() or default+ return ""def startup_authorization(setting: Setting) -> str:@@ -361,7 +365,7 @@ class GravitinoContext:f"metalake, but got {type(requested).__name__}.")- metalake = get_request_metalake() or self._setting.metalake+ metalake = get_request_metalake(self._setting.metalake)if not metalake:# Only point at the discovery tool when this deployment actually# exposes it; a tag filter can hide it, and naming a tool thediff --git a/mcp-server/mcp_server/core/errors.py b/mcp-server/mcp_server/core/errors.pynew file mode 100644index 0000000000..3b8c99e1d1--- /dev/null+++ b/mcp-server/mcp_server/core/errors.py@@ -0,0 +1,392 @@+# 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 asyncio+from dataclasses import dataclass+from typing import Optional++import httpx+from fastmcp.exceptions import (+ AuthorizationError,+ DisabledError,+ NotFoundError,+ ToolError,+)+from fastmcp.exceptions import ValidationError as FastMCPValidationError+from fastmcp.server.middleware.error_handling import ErrorHandlingMiddleware+from fastmcp.server.middleware.middleware import CallNext, MiddlewareContext+from fastmcp.tools.base import ToolResult+from mcp.shared.exceptions import McpError, UrlElicitationRequiredError+from mcp.types import ErrorData++from mcp_server.client.plain.exception import GravitinoException+from mcp_server.core.context import ServiceIdentityFallbackDisabled+from mcp_server.core.oauth import (+ OAuthTokenEndpointError,+ OAuthTokenResponseError,+)++# Standard JSON-RPC error codes and server-defined codes (-32000..-32099).+JSONRPC_INVALID_PARAMS = -32602+JSONRPC_INTERNAL_ERROR = -32603+JSONRPC_SERVER_ERROR = -32000+JSONRPC_NOT_FOUND = -32001+JSONRPC_RESOURCE_NOT_FOUND = -32002+JSONRPC_CONFLICT = -32009++# Gravitino REST ErrorConstants (org.apache.gravitino.dto.responses.ErrorConstants).+_GRAVITINO_ILLEGAL_ARGUMENTS_CODE = 1001+_GRAVITINO_NOT_FOUND_CODE = 1003+_GRAVITINO_ALREADY_EXISTS_CODE = 1004+_GRAVITINO_NON_EMPTY_CODE = 1005+_GRAVITINO_CONNECTION_FAILED_CODE = 1007+_GRAVITINO_FORBIDDEN_CODE = 1008+_GRAVITINO_NOT_IN_USE_CODE = 1009+_GRAVITINO_IN_USE_CODE = 1010+_GRAVITINO_UNAUTHORIZED_CODE = 1011+_GRAVITINO_OPTIMISTIC_LOCK_CONFLICT_CODE = 1012+_GRAVITINO_SERVICE_UNAVAILABLE_CODE = 1013++# (mcp_code, prefix, outcome, category, default_error_type)+_Rule = tuple[int, str, str, str, str]++_UNAUTHORIZED_RULE: _Rule = (+ JSONRPC_SERVER_ERROR,+ "Unauthorized",+ "deny",+ "unauthorized",+ "UnauthorizedException",+)+_PERMISSION_DENIED_RULE: _Rule = (+ JSONRPC_SERVER_ERROR,+ "Permission denied",+ "deny",+ "permission_denied",+ "ForbiddenException",+)+_INVALID_PARAMS_RULE: _Rule = (+ JSONRPC_INVALID_PARAMS,+ "Invalid params",+ "error",+ "invalid_params",+ "",+)+_NOT_FOUND_RULE: _Rule = (+ JSONRPC_NOT_FOUND,+ "Not found",+ "error",+ "not_found",+ "",+)+_CONFLICT_RULE: _Rule = (+ JSONRPC_CONFLICT,+ "Conflict",+ "error",+ "conflict",+ "",+)+_TIMEOUT_RULE: _Rule = (+ JSONRPC_SERVER_ERROR,+ "Request timeout",+ "error",+ "timeout",+ "",+)+_RATE_LIMIT_RULE: _Rule = (+ JSONRPC_SERVER_ERROR,+ "Rate limited",+ "error",+ "rate_limited",+ "",+)+_UNAVAILABLE_RULE: _Rule = (+ JSONRPC_INTERNAL_ERROR,+ "Internal error",+ "error",+ "unavailable",+ "",+)+_INTERNAL_ERROR_RULE: _Rule = (+ JSONRPC_INTERNAL_ERROR,+ "Internal error",+ "error",+ "internal_error",+ "",+)++_UPSTREAM_STATUS_RULES: dict[int, _Rule] = {+ 408: _TIMEOUT_RULE,+ 429: _RATE_LIMIT_RULE,+ 502: _UNAVAILABLE_RULE,+ 503: _UNAVAILABLE_RULE,+}++_HTTP_STATUS_RULES: dict[int, _Rule] = {+ **_UPSTREAM_STATUS_RULES,+ 400: _INVALID_PARAMS_RULE,+ 401: _UNAUTHORIZED_RULE,+ 403: _PERMISSION_DENIED_RULE,+ 404: _NOT_FOUND_RULE,+ 409: _CONFLICT_RULE,+ 422: _INVALID_PARAMS_RULE,+}++_GRAVITINO_CODE_RULES: dict[int, _Rule] = {+ _GRAVITINO_UNAUTHORIZED_CODE: _UNAUTHORIZED_RULE,+ _GRAVITINO_FORBIDDEN_CODE: _PERMISSION_DENIED_RULE,+ _GRAVITINO_ILLEGAL_ARGUMENTS_CODE: _INVALID_PARAMS_RULE,+ _GRAVITINO_NOT_FOUND_CODE: _NOT_FOUND_RULE,+ _GRAVITINO_ALREADY_EXISTS_CODE: _CONFLICT_RULE,+ _GRAVITINO_NON_EMPTY_CODE: _CONFLICT_RULE,+ _GRAVITINO_NOT_IN_USE_CODE: _CONFLICT_RULE,+ _GRAVITINO_IN_USE_CODE: _CONFLICT_RULE,+ _GRAVITINO_OPTIMISTIC_LOCK_CONFLICT_CODE: _CONFLICT_RULE,+ _GRAVITINO_CONNECTION_FAILED_CODE: _UNAVAILABLE_RULE,+ _GRAVITINO_SERVICE_UNAVAILABLE_CODE: _UNAVAILABLE_RULE,+}++_MCP_CODE_RULES: dict[int, _Rule] = {+ JSONRPC_INVALID_PARAMS: _INVALID_PARAMS_RULE,+ JSONRPC_NOT_FOUND: _NOT_FOUND_RULE,+ JSONRPC_RESOURCE_NOT_FOUND: _NOT_FOUND_RULE,+ JSONRPC_CONFLICT: _CONFLICT_RULE,+}+++@dataclass(frozen=True)+class ErrorClassification:+ """Normalized classification of a tool-call failure.++ Shared by MCP error transformation (JSON-RPC code and message prefix) and+ audit logging (outcome, error_type, error_category) so clients and audit+ logs agree on why a call failed.+ """++ mcp_code: int+ prefix: str+ outcome: str+ error_type: str+ category: str+++def _from_rule(+ rule: _Rule,+ *,+ error_type: str,+ fallback_type: str,+ method: str = "",+) -> ErrorClassification:+ mcp_code, prefix, outcome, category, rule_default_type = rule+ if mcp_code == JSONRPC_NOT_FOUND and method.startswith("resources/"):+ mcp_code = JSONRPC_RESOURCE_NOT_FOUND+ prefix = "Resource not found"+ resolved_type = error_type or rule_default_type or fallback_type+ return ErrorClassification(+ mcp_code=mcp_code,+ prefix=prefix,+ outcome=outcome,+ error_type=resolved_type,+ category=category,+ )+++def unwrap_exception(exc: BaseException) -> BaseException:+ """Unwrap MCP/FastMCP wrapper exceptions to find the underlying failure."""+ current = exc+ seen = set()+ while (+ isinstance(current, (McpError, ToolError))+ and current.__cause__ is not None+ and id(current.__cause__) not in seen+ ):+ seen.add(id(current))+ current = current.__cause__+ return current+++def _classify_http_status(+ status_code: Optional[int],+ *,+ error_type: str,+ default_error_type: str,+ method: str = "",+ token_endpoint: bool = False,+) -> Optional[ErrorClassification]:+ """Map an HTTP status code (>= 400) to an ErrorClassification, or None."""+ if status_code is None or status_code < 400:+ return None+ if token_endpoint:+ # The MCP server supplies the endpoint, credentials and scope.+ rule = _UPSTREAM_STATUS_RULES.get(status_code, _INTERNAL_ERROR_RULE)+ else:+ rule = _HTTP_STATUS_RULES.get(+ status_code,+ _INVALID_PARAMS_RULE if status_code < 500 else _INTERNAL_ERROR_RULE,+ )+ return _from_rule(+ rule,+ error_type=error_type,+ fallback_type=default_error_type,+ method=method,+ )+++def _classify_gravitino_exception(+ exc: GravitinoException, method: str = ""+) -> ErrorClassification:+ """Classify a GravitinoException using timeout cause, HTTP status, or error code."""+ if isinstance(exc.__cause__, httpx.TimeoutException) or (+ exc.error_type == "ReadTimeout"+ ):+ timeout_type = exc.error_type or type(exc.__cause__).__name__+ return _from_rule(+ _TIMEOUT_RULE,+ error_type=timeout_type,+ fallback_type="ReadTimeout",+ method=method,+ )++ by_status = _classify_http_status(+ exc.status_code,+ error_type=exc.error_type,+ default_error_type="GravitinoException",+ method=method,+ )+ if by_status is not None:+ return by_status++ rule = (+ _GRAVITINO_CODE_RULES.get(exc.error_code, _INTERNAL_ERROR_RULE)+ if exc.error_code is not None+ else _INTERNAL_ERROR_RULE+ )+ return _from_rule(+ rule,+ error_type=exc.error_type,+ fallback_type="GravitinoException",+ method=method,+ )+++def _classify_bare_mcp_error(exc: McpError) -> ErrorClassification:+ """Classify an McpError raised directly without an inner Python cause."""+ code = exc.error.code+ rule = _MCP_CODE_RULES.get(code)+ if rule is None and code == JSONRPC_SERVER_ERROR:+ message = (exc.error.message or "").lower()+ if "unauthorized" in message:+ rule = _UNAUTHORIZED_RULE+ elif "permission" in message or "forbidden" in message:+ rule = _PERMISSION_DENIED_RULE+ elif message.startswith("rate limited"):+ rule = _RATE_LIMIT_RULE+ elif "timeout" in message:+ rule = _TIMEOUT_RULE+ resolved = rule or _INTERNAL_ERROR_RULE+ return ErrorClassification(+ mcp_code=code,+ prefix=resolved[1],+ outcome=resolved[2],+ error_type="McpError",+ category=resolved[3],+ )+++def classify_error(exc: BaseException, method: str = "") -> ErrorClassification:+ """Classify any tool/middleware exception for MCP responses and audit logs."""+ root = unwrap_exception(exc)++ if isinstance(root, GravitinoException):+ return _classify_gravitino_exception(root, method=method)++ if isinstance(root, httpx.HTTPStatusError):+ by_status = _classify_http_status(+ root.response.status_code,+ error_type=type(root).__name__,+ default_error_type="HTTPStatusError",+ method=method,+ token_endpoint=isinstance(root, OAuthTokenEndpointError),+ )+ if by_status is not None:+ return by_status++ if isinstance(root, McpError):+ return _classify_bare_mcp_error(root)++ root_type = type(root).__name__+ rule = _INTERNAL_ERROR_RULE+ if isinstance(root, ServiceIdentityFallbackDisabled):+ rule = _UNAUTHORIZED_RULE+ elif isinstance(root, (PermissionError, AuthorizationError)):+ rule = _PERMISSION_DENIED_RULE+ elif isinstance(root, OAuthTokenResponseError):+ rule = _INTERNAL_ERROR_RULE+ elif isinstance(root, (ValueError, TypeError, FastMCPValidationError)):+ rule = _INVALID_PARAMS_RULE+ elif isinstance(+ root, (FileNotFoundError, KeyError, NotFoundError, DisabledError)+ ):+ rule = _NOT_FOUND_RULE+ elif isinstance(+ root, (TimeoutError, asyncio.TimeoutError, httpx.TimeoutException)+ ):+ rule = _TIMEOUT_RULE+ elif isinstance(root, httpx.RequestError):+ rule = _UNAVAILABLE_RULE++ return _from_rule(+ rule, error_type=root_type, fallback_type=root_type, method=method+ )+++class GravitinoErrorHandlingMiddleware(ErrorHandlingMiddleware):+ """Return classified tool execution failures and preserve MCP protocol errors."""++ async def on_message(self, context: MiddlewareContext, call_next: CallNext):+ try:+ return await call_next(context)+ except Exception as error:+ self._log_error(error, context)+ # The SDK handles URL elicitation as a protocol challenge.+ if not self.transform_errors or isinstance(+ error, UrlElicitationRequiredError+ ):+ raise++ classification = classify_error(error, method=context.method or "")+ if isinstance(error, McpError):+ if context.method != "tools/call":+ raise+ data = error.error+ else:+ data = ErrorData(+ code=classification.mcp_code,+ message=f"{classification.prefix}: {error}",+ )+ if context.method == "tools/call":+ # Raising here would make the SDK discard the code and keep only text.+ return ToolResult(+ content=data.message,+ is_error=True,+ meta={+ "org.apache.gravitino/error": {+ "code": data.code,+ "category": classification.category,+ }+ },+ )+ raise McpError(data) from errordiff --git a/mcp-server/mcp_server/core/oauth.py b/mcp-server/mcp_server/core/oauth.pyindex 17e1922a45..a0c1163535 100644--- a/mcp-server/mcp_server/core/oauth.py+++ b/mcp-server/mcp_server/core/oauth.py@@ -43,6 +43,14 @@ DEFAULT_REFRESH_SKEW_SECONDS = 60_TokenTuple = Union[tuple[str, str], tuple[str, str, Union[int, str]]]+class OAuthTokenEndpointError(httpx.HTTPStatusError):+ """The service identity's OAuth token endpoint returned an HTTP error."""+++class OAuthTokenResponseError(ValueError):+ """The identity provider returned an unusable token response."""++class RefreshableBearerAuth(OAuth2ClientCredentials):"""httpx-auth client-credentials with form POST and one 401 retry."""@@ -95,13 +103,10 @@ class RefreshableBearerAuth(OAuth2ClientCredentials):self._configure_client(client)try:response = client.post(self.token_url, data=data)- self._log_token_http_error(response)- response.raise_for_status()- body = response.json()+ return self._token_tuple(response)finally:if self.client is None:client.close()- return self._token_tuple(body)async def request_new_token_async(self) -> _TokenTuple:"""POST ``client_credentials`` without blocking the event loop."""@@ -111,10 +116,7 @@ class RefreshableBearerAuth(OAuth2ClientCredentials):async with httpx.AsyncClient() as client:client.timeout = self.timeoutresponse = await client.post(self.token_url, data=data)- self._log_token_http_error(response)- response.raise_for_status()- body = response.json()- return self._token_tuple(body)+ return self._token_tuple(response)def auth_flow(self, request: httpx.Request@@ -164,17 +166,42 @@ class RefreshableBearerAuth(OAuth2ClientCredentials):data["client_secret"] = self.client_secretreturn data- def _token_tuple(self, body: dict) -> _TokenTuple:+ def _token_tuple(self, response: httpx.Response) -> _TokenTuple:+ if not response.is_success:+ message = (+ f"OAuth token endpoint returned HTTP {response.status_code}"+ )+ _LOG.error("%s", message)+ raise OAuthTokenEndpointError(+ message, request=response.request, response=response+ )+ try:+ body = response.json()+ except ValueError as exc:+ raise OAuthTokenResponseError(+ "Invalid JSON in OAuth token response"+ ) from exc+ if not isinstance(body, dict):+ raise OAuthTokenResponseError(+ "OAuth token response must be a JSON object"+ )token = body.get(self.token_field_name)if not token or not isinstance(token, str):- raise ValueError("OAuth token response missing access_token")+ raise OAuthTokenResponseError(+ "OAuth token response missing access_token"+ )expires_in = body.get("expires_in")_LOG.info("Fetched OAuth access token")if expires_in:- return self.state, token, expires_in+ try:+ return self.state, token, int(expires_in)+ except (TypeError, ValueError, OverflowError) as exc:+ raise OAuthTokenResponseError(+ "Invalid expires_in in OAuth token response"+ ) from excjwt_expires_in = self._jwt_expires_in(token)if jwt_expires_in is None:- raise ValueError(+ raise OAuthTokenResponseError("OAuth token response omitted expires_in and ""access_token is not a JWT with exp")@@ -189,12 +216,12 @@ class RefreshableBearerAuth(OAuth2ClientCredentials):try:padded = parts[1] + "=" * (-len(parts[1]) % 4)payload = json.loads(base64.urlsafe_b64decode(padded))- exp = payload.get("exp")+ exp = payload.get("exp") if isinstance(payload, dict) else Noneif not RefreshableBearerAuth._is_numeric_date(exp):return Noneexpires_at = int(float(exp))return max(expires_at - int(time.time()), 1)- except (ValueError, json.JSONDecodeError, TypeError):+ except (ValueError, OverflowError, TypeError):return None@staticmethod@@ -212,13 +239,6 @@ class RefreshableBearerAuth(OAuth2ClientCredentials):return Falsereturn False- @staticmethod- def _log_token_http_error(response: httpx.Response) -> None:- if response.status_code >= 400:- _LOG.error(- "OAuth token request failed: HTTP %s", response.status_code- )-def _cached_bearer(self) -> Optional[str]:try:return OAuth2.token_cache.get_token(diff --git a/mcp-server/mcp_server/server.py b/mcp-server/mcp_server/server.pyindex 688e0d17d6..9d445fec78 100644--- a/mcp-server/mcp_server/server.py+++ b/mcp-server/mcp_server/server.py@@ -23,7 +23,6 @@ from urllib.parse import urlparseimport mcp.types as mtfrom fastmcp import FastMCP-from fastmcp.server.middleware.error_handling import ErrorHandlingMiddlewarefrom fastmcp.server.middleware.logging import (LoggingMiddleware,)@@ -43,6 +42,10 @@ from mcp_server.core.context import (get_request_metalake,service_fallback_authorization,)+from mcp_server.core.errors import (+ GravitinoErrorHandlingMiddleware,+ classify_error,+)from mcp_server.core.middleware import (TOOLS_WITHOUT_METALAKE,MetalakeArgumentMiddleware,@@ -86,7 +89,7 @@ class AuditMiddleware(Middleware):"""if tool_name in TOOLS_WITHOUT_METALAKE:return ""- return get_request_metalake() or self._default_metalake+ return get_request_metalake(self._default_metalake)async def on_call_tool(self,@@ -94,23 +97,34 @@ class AuditMiddleware(Middleware):call_next: CallNext[mt.CallToolRequestParams, ToolResult],) -> ToolResult:tool_name = context.message.name if context.message else "unknown"+ arguments = context.message.arguments if context.message else Noneprincipal = _get_principal_from_request(self._fallback_authorization)+ metalake = self._metalake(tool_name)+ target_type, target_name = audit.extract_write_target(+ tool_name, arguments, metalake+ )try:result = await call_next(context)audit.emit(principal=principal,tool=tool_name,outcome="allow",- metalake=self._metalake(tool_name),+ metalake=metalake,+ target_type=target_type,+ target_name=target_name,)return resultexcept Exception as exc:+ classification = classify_error(exc, method=context.method or "")audit.emit(principal=principal,tool=tool_name,- outcome="deny",- error_type=type(exc).__name__,- metalake=self._metalake(tool_name),+ outcome=classification.outcome,+ error_type=classification.error_type,+ error_category=classification.category,+ metalake=metalake,+ target_type=target_type,+ target_name=target_name,)raise@@ -137,6 +151,13 @@ def _create_gravitino_mcp(setting: Setting) -> FastMCP:# Added first so it wraps the others: it must publish the call's metalake# before AuditMiddleware records it.mcp.add_middleware(MetalakeArgumentMiddleware())+ # Audit the original exception before the error handler returns a tool result.+ mcp.add_middleware(+ GravitinoErrorHandlingMiddleware(+ include_traceback=True,+ transform_errors=True,+ )+ )mcp.add_middleware(AuditMiddleware(service_fallback_authorization(setting), setting.metalake@@ -146,12 +167,6 @@ def _create_gravitino_mcp(setting: Setting) -> FastMCP:LoggingMiddleware(include_payloads=True, max_payload_length=1000))mcp.add_middleware(TimingMiddleware())- mcp.add_middleware(- ErrorHandlingMiddleware(- include_traceback=True,- transform_errors=True,- )- )return mcpdiff --git a/mcp-server/tests/unit/test_audit.py b/mcp-server/tests/unit/test_audit.pyindex 23ba80b732..1e9c2777ee 100644--- a/mcp-server/tests/unit/test_audit.py+++ b/mcp-server/tests/unit/test_audit.py@@ -21,8 +21,9 @@ import hashlibimport jsonimport loggingimport unittest-from unittest.mock import patch+from unittest.mock import MagicMock, patch+import httpxfrom fastmcp import Clientfrom mcp_server.client.factory import RESTClientFactory@@ -314,30 +315,368 @@ class TestAuditMiddlewareIntegration(unittest.TestCase):self.assertEqual(record["principal"], "oauth:0d315e3c73d7840c")def test_failed_tool_call_emits_deny_record(self):- """A tool call that raises an exception produces an audit record with outcome=deny."""+ """An authorization denial produces outcome=deny with the original error_type."""class FailingOperation(MockOperation):def as_catalog_operation(self):- return _FailingCatalogOperation()+ return _FailingCatalogOperation(+ GravitinoException(+ "Error code: 1008, Error type: ForbiddenException, "+ "Error message: Not allowed",+ status_code=403,+ error_code=1008,+ error_type="ForbiddenException",+ )+ )RESTClientFactory.set_rest_client(FailingOperation)server = GravitinoMCPServer(Setting("mock_metalake"))async def _run():async with Client(server.mcp) as client:- try:- await client.call_tool("get_list_of_catalogs")- except Exception: # pylint: disable=broad-exception-caught- pass+ await client.call_tool(+ "get_list_of_catalogs", raise_on_error=False+ )asyncio.run(_run())- deny_records = [- json.loads(r) for r in self.log_records if '"deny"' in r+ self.assertEqual(len(self.log_records), 1)+ record = json.loads(self.log_records[0])+ self.assertEqual(record["tool"], "get_list_of_catalogs")+ self.assertEqual(record["outcome"], "deny")+ self.assertEqual(record["error_type"], "ForbiddenException")+ self.assertEqual(record["error_category"], "permission_denied")+ self.assertNotEqual(record["error_type"], "McpError")++ def test_non_authz_failures_emit_error_outcome_and_original_classification(+ self,+ ):+ """Non-authz failures emit outcome=error with their original error type and category."""+ request = httpx.Request("GET", "http://gravitino/api/metalakes")+ cases = [+ (+ GravitinoException(+ "Bad request",+ status_code=400,+ error_code=1001,+ error_type="IllegalArgumentException",+ ),+ "error",+ "IllegalArgumentException",+ "invalid_params",+ ),+ (+ GravitinoException(+ "Not found",+ status_code=404,+ error_code=1003,+ error_type="NoSuchTableException",+ ),+ "error",+ "NoSuchTableException",+ "not_found",+ ),+ (+ GravitinoException(+ "In use",+ status_code=409,+ error_code=1010,+ error_type="CatalogInUseException",+ ),+ "error",+ "CatalogInUseException",+ "conflict",+ ),+ (+ httpx.ConnectError("Connection refused", request=request),+ "error",+ "ConnectError",+ "unavailable",+ ),+ (+ GravitinoException(+ "Unauthenticated",+ status_code=401,+ error_code=1011,+ error_type="UnauthorizedException",+ ),+ "deny",+ "UnauthorizedException",+ "unauthorized",+ ),]- self.assertTrue(len(deny_records) >= 1)- self.assertEqual(deny_records[0]["tool"], "get_list_of_catalogs")- self.assertEqual(deny_records[0]["outcome"], "deny")++ for (+ exc_to_raise,+ expected_outcome,+ expected_type,+ expected_category,+ ) in cases:+ with self.subTest(expected_type=expected_type):+ self.log_records.clear()++ class FailingOperation(MockOperation):+ def as_catalog_operation(self, err=exc_to_raise):+ return _FailingCatalogOperation(err)++ RESTClientFactory.set_rest_client(FailingOperation)+ server = GravitinoMCPServer(Setting("mock_metalake"))++ async def _run(mcp=server.mcp):+ async with Client(mcp) as client:+ await client.call_tool(+ "get_list_of_catalogs", raise_on_error=False+ )++ asyncio.run(_run())++ self.assertEqual(len(self.log_records), 1)+ record = json.loads(self.log_records[0])+ self.assertEqual(record["outcome"], expected_outcome)+ self.assertEqual(record["error_type"], expected_type)+ self.assertEqual(record["error_category"], expected_category)++ def test_fallback_disabled_emits_deny_record(self):+ """--no-service-identity-fallback rejection is audited as outcome=deny."""+ server = GravitinoMCPServer(+ Setting(+ "mock_metalake",+ transport="http",+ token="service-token",+ no_service_identity_fallback=True,+ )+ )+ mock_request = MagicMock()+ mock_request.headers.get.return_value = ""++ async def _run():+ with patch(+ "fastmcp.server.dependencies.get_http_request",+ return_value=mock_request,+ ):+ async with Client(server.mcp) as client:+ await client.call_tool(+ "get_list_of_catalogs", raise_on_error=False+ )++ asyncio.run(_run())++ self.assertEqual(len(self.log_records), 1)+ record = json.loads(self.log_records[0])+ self.assertEqual(record["outcome"], "deny")+ self.assertEqual(+ record["error_type"], "ServiceIdentityFallbackDisabled"+ )+ self.assertEqual(record["error_category"], "unauthorized")++ def test_write_and_delete_tools_record_target_object_on_allow_and_deny(+ self,+ ):+ """Write/delete audit records include target_type and target_name."""++ async def _run_allow():+ async with Client(self.mcp) as client:+ await client.call_tool(+ "drop_schema",+ {+ "catalog_name": "mcpcat",+ "schema_name": "alice_s",+ "metalake": "authz",+ },+ )+ await client.call_tool(+ "drop_catalog",+ {"catalog_name": "mcpcat"},+ )++ asyncio.run(_run_allow())++ schema_record = json.loads(self.log_records[0])+ self.assertEqual(schema_record["outcome"], "allow")+ self.assertEqual(schema_record["metalake"], "authz")+ self.assertEqual(schema_record["target_type"], "schema")+ self.assertEqual(schema_record["target_name"], "authz.mcpcat.alice_s")++ catalog_record = json.loads(self.log_records[1])+ self.assertEqual(catalog_record["outcome"], "allow")+ self.assertEqual(catalog_record["target_type"], "catalog")+ self.assertEqual(catalog_record["target_name"], "mock_metalake.mcpcat")++ # Denied drop_table must still carry its target object.+ self.log_records.clear()++ class _DeniedTableOp:+ async def drop_table(self, *_args, **_kwargs):+ raise GravitinoException(+ "Forbidden",+ status_code=403,+ error_code=1008,+ error_type="ForbiddenException",+ )++ class DeniedOperation(MockOperation):+ def as_table_operation(self):+ return _DeniedTableOp()++ RESTClientFactory.set_rest_client(DeniedOperation)+ denied_server = GravitinoMCPServer(Setting("authz"))++ async def _run_deny():+ async with Client(denied_server.mcp) as client:+ await client.call_tool(+ "drop_table",+ {+ "catalog_name": "mcpcat",+ "schema_name": "alice_s",+ "table_name": "orders",+ },+ raise_on_error=False,+ )++ asyncio.run(_run_deny())++ denied_record = json.loads(self.log_records[0])+ self.assertEqual(denied_record["outcome"], "deny")+ self.assertEqual(denied_record["error_type"], "ForbiddenException")+ self.assertEqual(denied_record["target_type"], "table")+ self.assertEqual(+ denied_record["target_name"], "authz.mcpcat.alice_s.orders"+ )++ def test_readonly_tool_omits_target_fields(self):+ """Read-only calls do not emit target_type or target_name."""++ async def _run():+ async with Client(self.mcp) as client:+ await client.call_tool("get_list_of_catalogs")++ asyncio.run(_run())++ record = json.loads(self.log_records[0])+ self.assertNotIn("target_type", record)+ self.assertNotIn("target_name", record)+++class TestExtractWriteTarget(unittest.TestCase):+ """Unit tests for audit.extract_write_target() and write-tool coverage."""++ def test_extracts_hierarchical_and_special_targets(self):+ self.assertEqual(+ audit.extract_write_target(+ "link_model_version",+ {"catalog_name": "c", "schema_name": "s", "model_name": "m"},+ "ml",+ ),+ ("model", "ml.c.s.m"),+ )+ self.assertEqual(+ audit.extract_write_target(+ "create_table",+ {"catalog_name": "c", "schema_name": "s", "name": "t"},+ "ml",+ ),+ ("table", "ml.c.s.t"),+ )+ self.assertEqual(+ audit.extract_write_target(+ "alter_model_version",+ {+ "catalog_name": "c",+ "schema_name": "s",+ "model_name": "m",+ "version": 0,+ },+ "ml",+ ),+ ("model_version", "ml.c.s.m.0"),+ )+ self.assertEqual(+ audit.extract_write_target(+ "associate_tag_with_metadata",+ {+ "metadata_type": "TABLE",+ "metadata_full_name": "c.s.t",+ "tags_to_associate": ["pii"],+ },+ "ml",+ ),+ ("table", "ml.c.s.t"),+ )+ self.assertEqual(+ audit.extract_write_target(+ "associate_tag_with_metadata",+ {+ "metadata_type": "metalake",+ "metadata_full_name": "ml",+ "tags_to_associate": ["pii"],+ },+ "ml",+ ),+ ("metalake", "ml"),+ )+ self.assertEqual(+ audit.extract_write_target(+ "cancel_job", {"job_id": "job-42"}, "ml"+ ),+ ("job", "job-42"),+ )+ self.assertEqual(+ audit.extract_write_target(+ "drop_schema", {"catalog_name": "c", "schema_name": "s"}, ""+ ),+ ("", ""),+ )++ def test_missing_or_invalid_arguments_return_empty_target(self):+ self.assertEqual(+ audit.extract_write_target(+ "drop_table", {"catalog_name": "c"}, "ml"+ ),+ ("", ""),+ )+ self.assertEqual(+ audit.extract_write_target(+ "alter_model_version",+ {+ "catalog_name": "c",+ "schema_name": "s",+ "model_name": "m",+ "version": 1.5,+ },+ "ml",+ ),+ ("", ""),+ )+ self.assertEqual(+ audit.extract_write_target("drop_catalog", None, "ml"), ("", "")+ )+ self.assertEqual(+ audit.extract_write_target("get_list_of_catalogs", {}, "ml"),+ ("", ""),+ )++ def test_every_mutating_registered_tool_has_a_write_target_spec(self):+ """Keep WRITE_TARGET_SPECS synchronized with the registered MCP tools."""+ RESTClientFactory.set_rest_client(MockOperation)+ try:+ server = GravitinoMCPServer(Setting("ml"))+ tools = asyncio.run(server.mcp.list_tools())+ finally:+ RESTClientFactory.set_rest_client(PlainRESTClientOperation)++ registered_names = {tool.name for tool in tools}+ # Every configured spec must name an actual registered tool.+ self.assertLessEqual(+ set(audit.WRITE_TARGET_SPECS.keys()), registered_names+ )++ readonly_prefixes = ("get_", "list_", "load_", "metadata_type_")+ mutating_tools = {+ name+ for name in registered_names+ if not name.startswith(readonly_prefixes)+ }+ self.assertEqual(mutating_tools, set(audit.WRITE_TARGET_SPECS.keys()))# ---------------------------------------------------------------------------@@ -357,8 +696,11 @@ class _CapturingHandler(logging.Handler):class _FailingCatalogOperation:+ def __init__(self, exc: Exception):+ self._exc = exc+async def get_list_of_catalogs(self) -> str:- raise GravitinoException("Error code: 1003, Error type: FORBIDDEN")+ raise self._excdef _jwt_for(subject: str, signature: bytes = b"signature") -> str:diff --git a/mcp-server/tests/unit/test_error_handling.py b/mcp-server/tests/unit/test_error_handling.pynew file mode 100644index 0000000000..fc4a00cf35--- /dev/null+++ b/mcp-server/tests/unit/test_error_handling.py@@ -0,0 +1,817 @@+# 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.++"""Unit tests for Gravitino error metadata and MCP error classification."""++import asyncio+import json+import unittest+from unittest.mock import AsyncMock, MagicMock, patch++import httpx+from fastmcp import Client+from fastmcp.exceptions import NotFoundError, ToolError+from mcp.shared.exceptions import McpError, UrlElicitationRequiredError+from mcp.types import ErrorData++from mcp_server.client.factory import RESTClientFactory+from mcp_server.client.plain.exception import GravitinoException+from mcp_server.client.plain.plain_rest_client_operation import (+ PlainRESTClientOperation,+ _GravitinoAsyncClient,+)+from mcp_server.client.plain.utils import (+ extract_content_from_response,+ extract_list_from_response,+ extract_response,+)+from mcp_server.core.context import ServiceIdentityFallbackDisabled+from mcp_server.core.errors import (+ JSONRPC_CONFLICT,+ JSONRPC_INTERNAL_ERROR,+ JSONRPC_INVALID_PARAMS,+ JSONRPC_NOT_FOUND,+ JSONRPC_RESOURCE_NOT_FOUND,+ JSONRPC_SERVER_ERROR,+ GravitinoErrorHandlingMiddleware,+ classify_error,+)+from mcp_server.core.setting import Setting+from mcp_server.server import GravitinoMCPServer++# Tests intentionally exercise internal REST client hooks to inject MockTransport.+# pylint: disable=protected-access+++class TestRestResponseExceptionMetadata(unittest.TestCase):+ """REST response extractors attach HTTP status, code, and type to GravitinoException."""++ def test_extract_content_attaches_status_code_and_type(self):+ response = httpx.Response(+ 403,+ json={+ "code": 1008,+ "type": "ForbiddenException",+ "message": "User 'alice' is not authorized",+ },+ )+ with self.assertRaises(GravitinoException) as raised:+ extract_content_from_response(response, "table", {})++ exc = raised.exception+ self.assertEqual(exc.status_code, 403)+ self.assertEqual(exc.error_code, 1008)+ self.assertEqual(exc.error_type, "ForbiddenException")+ self.assertIn("User 'alice' is not authorized", str(exc))++ def test_extract_response_attaches_status_code_and_type(self):+ response = httpx.Response(+ 409,+ json={+ "code": 1010,+ "type": "CatalogInUseException",+ "message": "Catalog is in use",+ },+ )+ with self.assertRaises(GravitinoException) as raised:+ extract_response(response)++ exc = raised.exception+ self.assertEqual(exc.status_code, 409)+ self.assertEqual(exc.error_code, 1010)+ self.assertEqual(exc.error_type, "CatalogInUseException")++ def test_extract_list_attaches_status_code_and_type(self):+ response = httpx.Response(+ 404,+ content=json.dumps(+ {+ "code": 1003,+ "type": "NoSuchSchemaException",+ "message": "Schema not found",+ }+ ).encode("utf-8"),+ )+ with self.assertRaises(GravitinoException) as raised:+ extract_list_from_response(response, "identifiers")++ exc = raised.exception+ self.assertEqual(exc.status_code, 404)+ self.assertEqual(exc.error_code, 1003)+ self.assertEqual(exc.error_type, "NoSuchSchemaException")++ def test_malformed_200_response_has_no_client_error_status(self):+ response = httpx.Response(+ 200,+ request=httpx.Request("GET", "http://gravitino/api/test"),+ content=b"not json",+ )+ for extract, args in (+ (extract_response, ()),+ (extract_content_from_response, ("table",)),+ (extract_list_from_response, ("identifiers",)),+ ):+ with self.subTest(extract=extract.__name__):+ with self.assertRaises(GravitinoException) as raised:+ extract(response, *args)+ self.assertIsInstance(raised.exception.__cause__, ValueError)+ classification = classify_error(raised.exception)+ self.assertEqual(+ classification.mcp_code, JSONRPC_INTERNAL_ERROR+ )+ self.assertEqual(classification.category, "internal_error")+++class TestClassifyError(unittest.TestCase):+ """classify_error maps Gravitino, HTTP, and Python errors consistently."""++ def test_gravitino_http_status_mapping(self):+ cases = [+ (+ 401,+ 1011,+ "UnauthorizedException",+ JSONRPC_SERVER_ERROR,+ "Unauthorized",+ "deny",+ "unauthorized",+ ),+ (+ 403,+ 1008,+ "ForbiddenException",+ JSONRPC_SERVER_ERROR,+ "Permission denied",+ "deny",+ "permission_denied",+ ),+ (+ 400,+ 1001,+ "IllegalArgumentException",+ JSONRPC_INVALID_PARAMS,+ "Invalid params",+ "error",+ "invalid_params",+ ),+ (+ 404,+ 1003,+ "NoSuchTableException",+ JSONRPC_NOT_FOUND,+ "Not found",+ "error",+ "not_found",+ ),+ (+ 409,+ 1004,+ "TableAlreadyExistsException",+ JSONRPC_CONFLICT,+ "Conflict",+ "error",+ "conflict",+ ),+ (+ 409,+ 1010,+ "CatalogInUseException",+ JSONRPC_CONFLICT,+ "Conflict",+ "error",+ "conflict",+ ),+ (+ 500,+ 1002,+ "RuntimeException",+ JSONRPC_INTERNAL_ERROR,+ "Internal error",+ "error",+ "internal_error",+ ),+ (+ 502,+ 1007,+ "ConnectionFailedException",+ JSONRPC_INTERNAL_ERROR,+ "Internal error",+ "error",+ "unavailable",+ ),+ (+ 503,+ 1013,+ "ServiceUnavailableException",+ JSONRPC_INTERNAL_ERROR,+ "Internal error",+ "error",+ "unavailable",+ ),+ ]+ for (+ status,+ code,+ err_type,+ expected_mcp_code,+ expected_prefix,+ expected_outcome,+ expected_category,+ ) in cases:+ with self.subTest(status=status, err_type=err_type):+ exc = GravitinoException(+ "detail",+ status_code=status,+ error_code=code,+ error_type=err_type,+ )+ result = classify_error(exc)+ self.assertEqual(result.mcp_code, expected_mcp_code)+ self.assertEqual(result.prefix, expected_prefix)+ self.assertEqual(result.outcome, expected_outcome)+ self.assertEqual(result.error_type, err_type)+ self.assertEqual(result.category, expected_category)++ def test_gravitino_error_code_fallback_without_http_status(self):+ cases = [+ (+ 1011,+ "UnauthorizedException",+ JSONRPC_SERVER_ERROR,+ "deny",+ ),+ (1008, "ForbiddenException", JSONRPC_SERVER_ERROR, "deny"),+ (1001, "IllegalArgumentException", JSONRPC_INVALID_PARAMS, "error"),+ (1003, "NoSuchTableException", JSONRPC_NOT_FOUND, "error"),+ (1004, "AlreadyExistsException", JSONRPC_CONFLICT, "error"),+ (1005, "NonEmptySchemaException", JSONRPC_CONFLICT, "error"),+ (1009, "CatalogNotInUseException", JSONRPC_CONFLICT, "error"),+ (1010, "CatalogInUseException", JSONRPC_CONFLICT, "error"),+ (1012, "OptimisticLockException", JSONRPC_CONFLICT, "error"),+ (+ 1007,+ "ConnectionFailedException",+ JSONRPC_INTERNAL_ERROR,+ "error",+ ),+ (+ 1013,+ "ServiceUnavailableException",+ JSONRPC_INTERNAL_ERROR,+ "error",+ ),+ ]+ for error_code, error_type, expected_code, expected_outcome in cases:+ with self.subTest(error_code=error_code):+ exc = GravitinoException(+ "msg", error_code=error_code, error_type=error_type+ )+ result = classify_error(exc)+ self.assertEqual(result.mcp_code, expected_code)+ self.assertEqual(result.outcome, expected_outcome)+ self.assertEqual(result.error_type, error_type)++ def test_unwraps_nested_mcp_and_tool_errors(self):+ root = GravitinoException(+ "denied",+ status_code=403,+ error_code=1008,+ error_type="ForbiddenException",+ )+ tool_err = ToolError("Error calling tool 'drop_table': denied")+ tool_err.__cause__ = root+ mcp_err = McpError(+ ErrorData(code=JSONRPC_SERVER_ERROR, message="Permission denied")+ )+ mcp_err.__cause__ = tool_err++ result = classify_error(mcp_err)+ self.assertEqual(result.outcome, "deny")+ self.assertEqual(result.error_type, "ForbiddenException")+ self.assertEqual(result.category, "permission_denied")++ def test_non_json_http_status_error_and_connection_errors(self):+ request = httpx.Request("GET", "http://gravitino/api/metalakes")+ for status, expected_code, expected_outcome, expected_cat in [+ (401, JSONRPC_SERVER_ERROR, "deny", "unauthorized"),+ (403, JSONRPC_SERVER_ERROR, "deny", "permission_denied"),+ (400, JSONRPC_INVALID_PARAMS, "error", "invalid_params"),+ (404, JSONRPC_NOT_FOUND, "error", "not_found"),+ (409, JSONRPC_CONFLICT, "error", "conflict"),+ (503, JSONRPC_INTERNAL_ERROR, "error", "unavailable"),+ (500, JSONRPC_INTERNAL_ERROR, "error", "internal_error"),+ ]:+ resp = httpx.Response(status, request=request, text="plain error")+ exc = httpx.HTTPStatusError("err", request=request, response=resp)+ result = classify_error(exc)+ self.assertEqual(result.mcp_code, expected_code)+ self.assertEqual(result.outcome, expected_outcome)+ self.assertEqual(result.category, expected_cat)++ connect_err = httpx.ConnectError(+ "All connection attempts failed", request=request+ )+ connect_res = classify_error(connect_err)+ self.assertEqual(connect_res.mcp_code, JSONRPC_INTERNAL_ERROR)+ self.assertEqual(connect_res.outcome, "error")+ self.assertEqual(connect_res.error_type, "ConnectError")+ self.assertEqual(connect_res.category, "unavailable")++ def test_python_and_fastmcp_exceptions(self):+ res = classify_error(ServiceIdentityFallbackDisabled("no header"))+ self.assertEqual(res.mcp_code, JSONRPC_SERVER_ERROR)+ self.assertEqual(res.outcome, "deny")+ self.assertEqual(res.category, "unauthorized")++ res = classify_error(NotFoundError("missing"), method="resources/read")+ self.assertEqual(res.mcp_code, JSONRPC_RESOURCE_NOT_FOUND)+ self.assertEqual(res.prefix, "Resource not found")++ res = classify_error(PermissionError("no access"))+ self.assertEqual(res.outcome, "deny")+ self.assertEqual(res.category, "permission_denied")++ res = classify_error(ValueError("bad input"))+ self.assertEqual(res.mcp_code, JSONRPC_INVALID_PARAMS)+ self.assertEqual(res.outcome, "error")++ res = classify_error(RuntimeError("unexpected"))+ self.assertEqual(res.mcp_code, JSONRPC_INTERNAL_ERROR)+ self.assertEqual(res.outcome, "error")+ self.assertEqual(res.error_type, "RuntimeError")+++class TestProtocolErrors(unittest.IsolatedAsyncioTestCase):+ async def test_protocol_errors_keep_their_code_and_data(self):+ middleware = GravitinoErrorHandlingMiddleware()+ challenge = UrlElicitationRequiredError([])+ native = McpError(+ ErrorData(+ code=-32602,+ message="Invalid resource URI",+ data={"field": "uri"},+ )+ )+ for method, error in (+ ("tools/call", challenge),+ ("resources/read", native),+ ):+ with self.subTest(method=method):+ with self.assertRaises(McpError) as raised:+ await middleware.on_message(+ MagicMock(method=method), AsyncMock(side_effect=error)+ )+ self.assertIs(raised.exception, error)+++class TestEndToEndMcpErrorMapping(unittest.TestCase):+ """Verify Gravitino REST responses map to distinct MCP errors through the full stack."""++ def setUp(self):+ RESTClientFactory.set_rest_client(PlainRESTClientOperation)++ def _call_with_transport(+ self,+ handler,+ tool_name: str,+ arguments: dict,+ setting: Setting | None = None,+ ):+ original_init = _GravitinoAsyncClient.__init__++ def init_with_transport(client, *args, **kwargs):+ kwargs["transport"] = httpx.MockTransport(handler)+ original_init(client, *args, **kwargs)++ async def _run():+ with patch.object(+ _GravitinoAsyncClient, "__init__", init_with_transport+ ):+ server = GravitinoMCPServer(+ setting or Setting(metalake="authz")+ )+ async with Client(server.mcp) as client:+ return await client.call_tool_mcp(tool_name, arguments)++ return asyncio.run(_run())++ def test_gravitino_rest_errors_are_not_reported_as_internal_error(self):+ cases = [+ (+ 403,+ 1008,+ "ForbiddenException",+ "User 'alice' is not authorized to drop table",+ JSONRPC_SERVER_ERROR,+ "Permission denied:",+ ),+ (+ 401,+ 1011,+ "UnauthorizedException",+ "Authentication required",+ JSONRPC_SERVER_ERROR,+ "Unauthorized:",+ ),+ (+ 400,+ 1001,+ "IllegalArgumentException",+ "Malformed json request",+ JSONRPC_INVALID_PARAMS,+ "Invalid params:",+ ),+ (+ 404,+ 1003,+ "NoSuchTableException",+ "Table does not exist",+ JSONRPC_NOT_FOUND,+ "Not found:",+ ),+ (+ 409,+ 1010,+ "CatalogInUseException",+ "Catalog is still in use",+ JSONRPC_CONFLICT,+ "Conflict:",+ ),+ ]+ for (+ status,+ code,+ err_type,+ detail,+ expected_mcp_code,+ expected_prefix,+ ) in cases:+ with self.subTest(status=status, err_type=err_type):++ def handler(+ _request,+ st=status,+ ec=code,+ et=err_type,+ msg=detail,+ ):+ return httpx.Response(+ st, json={"code": ec, "type": et, "message": msg}+ )++ result = self._call_with_transport(+ handler,+ "drop_table",+ {+ "catalog_name": "cat",+ "schema_name": "sch",+ "table_name": "tbl",+ },+ )+ self.assertTrue(result.isError)+ text = " ".join(item.text for item in result.content)+ self.assertTrue(text.startswith(expected_prefix), text)+ self.assertNotIn("Internal error:", text)+ self.assertIn(detail, text)+ self.assertEqual(+ result.meta["org.apache.gravitino/error"]["code"],+ expected_mcp_code,+ )++ def test_cancel_job_denials_reach_client_and_audit(self):+ for status, rest_code, error_type, category, prefix in (+ (+ 401,+ 1011,+ "UnauthorizedException",+ "unauthorized",+ "Unauthorized:",+ ),+ (+ 403,+ 1008,+ "ForbiddenException",+ "permission_denied",+ "Permission denied:",+ ),+ ):+ with self.subTest(status=status):++ handler = MagicMock(+ return_value=httpx.Response(+ status,+ json={+ "code": rest_code,+ "type": error_type,+ "message": "Cannot cancel this job",+ },+ )+ )++ with patch("mcp_server.server.audit.emit") as emit:+ result = self._call_with_transport(+ handler, "cancel_job", {"job_id": "job-42"}+ )+ handler.assert_called_once()+ request = handler.call_args.args[0]+ self.assertEqual(request.method, "POST")+ self.assertEqual(+ request.url.path, "/api/metalakes/authz/jobs/runs/job-42"+ )+ self.assertTrue(result.isError)+ self.assertTrue(result.content[0].text.startswith(prefix))+ self.assertIn("Cannot cancel this job", result.content[0].text)+ self.assertEqual(+ result.meta["org.apache.gravitino/error"],+ {+ "code": JSONRPC_SERVER_ERROR,+ "category": category,+ },+ )+ emit.assert_called_once_with(+ principal="anonymous",+ tool="cancel_job",+ outcome="deny",+ error_type=error_type,+ error_category=category,+ metalake="authz",+ target_type="job",+ target_name="job-42",+ )++ def test_unresolved_metalake_omits_tenant_and_target_from_audit(self):+ for default, arguments in (("prod", {"metalake": False}), ("", {})):+ with self.subTest(default=default, arguments=arguments):+ rest = MagicMock()+ with patch("mcp_server.core.audit._audit_logger.info") as log:+ result = self._call_with_transport(+ rest,+ "drop_table",+ {+ "catalog_name": "c",+ "schema_name": "s",+ "table_name": "t",+ **arguments,+ },+ setting=Setting(metalake=default),+ )+ self.assertTrue(result.isError)+ self.assertEqual(+ result.meta["org.apache.gravitino/error"],+ {+ "code": JSONRPC_INVALID_PARAMS,+ "category": "invalid_params",+ },+ )+ rest.assert_not_called()+ log.assert_called_once()+ record = json.loads(log.call_args.args[0])+ self.assertEqual(record["outcome"], "error")+ self.assertEqual(record["error_category"], "invalid_params")+ for field in ("metalake", "target_type", "target_name"):+ self.assertNotIn(field, record)++ def test_model_version_audit_matches_the_rest_target(self):+ for version in (1.0, "01", True):+ with self.subTest(version=version):+ handler = MagicMock(+ return_value=httpx.Response(+ 200, json={"code": 0, "dropped": True}+ )+ )+ with patch("mcp_server.server.audit.emit") as emit:+ result = self._call_with_transport(+ handler,+ "delete_model_version",+ {+ "catalog_name": "c",+ "schema_name": "s",+ "model_name": " m ",+ "version": version,+ },+ )+ self.assertFalse(result.isError)+ self.assertEqual(+ handler.call_args.args[0].url.path,+ "/api/metalakes/authz/catalogs/c/schemas/s/models/ m /versions/1",+ )+ self.assertEqual(+ emit.call_args.kwargs["target_name"], "authz.c.s. m .1"+ )+ self.assertEqual(+ emit.call_args.kwargs["target_type"], "model_version"+ )++ def test_connection_failure_and_5xx_remain_internal_error(self):+ def connect_handler(request):+ raise httpx.ConnectError(+ "All connection attempts failed", request=request+ )++ result = self._call_with_transport(+ connect_handler, "get_list_of_catalogs", {}+ )+ self.assertTrue(result.isError)+ text = " ".join(item.text for item in result.content)+ self.assertTrue(text.startswith("Internal error:"), text)+ self.assertEqual(+ result.meta["org.apache.gravitino/error"]["code"],+ JSONRPC_INTERNAL_ERROR,+ )++ def server_err_handler(_request):+ return httpx.Response(+ 500,+ json={+ "code": 1002,+ "type": "RuntimeException",+ "message": "Server boom",+ },+ )++ result = self._call_with_transport(+ server_err_handler, "get_list_of_catalogs", {}+ )+ self.assertTrue(result.isError)+ text = " ".join(item.text for item in result.content)+ self.assertTrue(text.startswith("Internal error:"), text)+ self.assertIn("Server boom", text)+ self.assertEqual(+ result.meta["org.apache.gravitino/error"]["code"],+ JSONRPC_INTERNAL_ERROR,+ )++ def test_upstream_rate_limit_is_reported_to_client_and_audit(self):+ for response in (+ httpx.Response(429, text="Too many requests"),+ httpx.Response(+ 429,+ json={+ "code": 429,+ "type": "RateLimit",+ "message": "Too many requests",+ },+ ),+ ):+ with self.subTest(response=response), patch(+ "mcp_server.server.audit.emit"+ ) as emit:+ result = self._call_with_transport(+ MagicMock(return_value=response), "get_list_of_catalogs", {}+ )+ self.assertTrue(result.isError)+ self.assertTrue(+ result.content[0].text.startswith("Rate limited:")+ )+ self.assertEqual(+ result.meta["org.apache.gravitino/error"],+ {"code": -32000, "category": "rate_limited"},+ )+ self.assertEqual(emit.call_args.kwargs["outcome"], "error")+ self.assertEqual(+ emit.call_args.kwargs["error_category"], "rate_limited"+ )++ def _assert_oauth_failure(self, response, code, category, error_type):+ setting = Setting(+ metalake="m",+ oauth_token_endpoint="https://idp.example/token",+ oauth_client_id="client",+ oauth_client_secret="secret",+ )+ idp = MagicMock(return_value=response)+ rest = MagicMock()+ with patch(+ "mcp_server.core.oauth.httpx.AsyncClient",+ return_value=httpx.AsyncClient(transport=httpx.MockTransport(idp)),+ ), patch("mcp_server.core.audit._audit_logger.info") as log:+ result = self._call_with_transport(+ rest, "get_list_of_catalogs", {}, setting=setting+ )+ idp.assert_called_once()+ rest.assert_not_called()+ self.assertTrue(result.isError)+ self.assertEqual(+ result.meta["org.apache.gravitino/error"],+ {"code": code, "category": category},+ )+ log.assert_called_once()+ record = json.loads(log.call_args.args[0])+ self.assertEqual(record["error_type"], error_type)+ self.assertEqual(record["error_category"], category)+ self.assertEqual(record["outcome"], "error")+ return result.content[0].text++ def test_malformed_oauth_responses_are_upstream_errors(self):+ for body in (+ b"{}",+ b"bad JSON",+ b"[]",+ b'{"access_token":"opaque","expires_in":"invalid"}',+ ):+ with self.subTest(body=body):+ text = self._assert_oauth_failure(+ httpx.Response(200, content=body),+ JSONRPC_INTERNAL_ERROR,+ "internal_error",+ "OAuthTokenResponseError",+ )+ self.assertIn("OAuth token response", text)++ def test_oauth_endpoint_failures_are_distinct_from_gravitino_errors(self):+ for status, code, category in (+ (400, JSONRPC_INTERNAL_ERROR, "internal_error"),+ (401, JSONRPC_INTERNAL_ERROR, "internal_error"),+ (403, JSONRPC_INTERNAL_ERROR, "internal_error"),+ (404, JSONRPC_INTERNAL_ERROR, "internal_error"),+ (408, JSONRPC_SERVER_ERROR, "timeout"),+ (429, JSONRPC_SERVER_ERROR, "rate_limited"),+ (503, JSONRPC_INTERNAL_ERROR, "unavailable"),+ ):+ with self.subTest(status=status):+ text = self._assert_oauth_failure(+ httpx.Response(status, json={"error": "invalid_client"}),+ code,+ category,+ "OAuthTokenEndpointError",+ )+ if category == "internal_error":+ self.assertIn(+ f"OAuth token endpoint returned HTTP {status}", text+ )++ def test_read_timeout_maps_to_request_timeout_with_actionable_text(self):+ def timeout_handler(request):+ raise httpx.ReadTimeout("slow", request=request)++ result = self._call_with_transport(+ timeout_handler,+ "get_table_metadata_details",+ {"catalog_name": "c", "schema_name": "s", "table_name": "t"},+ setting=Setting(metalake="m", gravitino_read_timeout=30),+ )+ self.assertTrue(result.isError)+ text = " ".join(item.text for item in result.content)+ self.assertTrue(text.startswith("Request timeout:"), text)+ self.assertIn("30 seconds", text)+ self.assertIn("may still complete", text)+ self.assertEqual(+ result.meta["org.apache.gravitino/error"]["code"],+ JSONRPC_SERVER_ERROR,+ )++ def test_missing_required_tool_argument_maps_to_invalid_params(self):+ def unused_handler(_request):+ raise AssertionError("HTTP call should not be reached")++ result = self._call_with_transport(unused_handler, "drop_table", {})+ self.assertTrue(result.isError)+ text = " ".join(item.text for item in result.content)+ self.assertTrue(text.startswith("Invalid params:"), text)+ self.assertEqual(+ result.meta["org.apache.gravitino/error"]["code"],+ JSONRPC_INVALID_PARAMS,+ )++ def test_service_identity_fallback_disabled_maps_to_unauthorized(self):+ def unused_handler(_request):+ raise AssertionError("HTTP call should not be reached")++ mock_request = MagicMock()+ mock_request.headers.get.return_value = ""+ with patch(+ "fastmcp.server.dependencies.get_http_request",+ return_value=mock_request,+ ):+ result = self._call_with_transport(+ unused_handler,+ "get_list_of_catalogs",+ {},+ setting=Setting(+ metalake="authz",+ transport="http",+ token="static-token",+ no_service_identity_fallback=True,+ ),+ )+ self.assertTrue(result.isError)+ text = " ".join(item.text for item in result.content)+ self.assertTrue(text.startswith("Unauthorized:"), text)+ self.assertEqual(+ result.meta["org.apache.gravitino/error"]["code"],+ JSONRPC_SERVER_ERROR,+ )