helios-mcp 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ tpcds/
2
+ *.parquet
3
+ __pycache__/
4
+ .env
5
+ .env.sh
6
+ /requirements.lock
7
+ .helios-python/
8
+ state/
9
+ *.db-wal
10
+ *.db-shm
11
+ node_modules/
12
+ *.tsbuildinfo
13
+ .cursor/
14
+ runs/
15
+ run_archive/
16
+ .DS_Store
17
+ *.pptx
18
+ .venv/
@@ -0,0 +1,152 @@
1
+ Metadata-Version: 2.5
2
+ Name: helios-mcp
3
+ Version: 0.3.0
4
+ Summary: Helios tools over MCP on stdio, for one developer's local agent (Claude Code, Cursor, goose, Mistral Vibe)
5
+ Project-URL: Homepage, https://github.com/christopheraburns/helios
6
+ Project-URL: Documentation, https://github.com/christopheraburns/helios/tree/main/packages/helios-mcp#readme
7
+ Project-URL: Repository, https://github.com/christopheraburns/helios
8
+ Project-URL: Issues, https://github.com/christopheraburns/helios/issues
9
+ Author: Helios Team
10
+ License-Expression: Apache-2.0
11
+ Keywords: agents,mcp,model context protocol,semantic layer,text-to-sql
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Database
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: helios-serve>=0.3.0
24
+ Requires-Dist: jsonschema>=4.23.0
25
+ Requires-Dist: mcp<3,>=2.2.0
26
+ Requires-Dist: pyyaml>=6.0.0
27
+ Description-Content-Type: text/markdown
28
+
29
+ # helios-mcp
30
+
31
+ The Helios tools over MCP on stdio, for one developer's local agent: Claude Code,
32
+ Cursor, goose, Mistral Vibe or any other MCP client.
33
+
34
+ ```sh
35
+ pip install helios-mcp
36
+ helios mcp --help
37
+ ```
38
+
39
+ You don't run `helios mcp` by hand: your agent launches it and talks to it over its
40
+ stdin and stdout.
41
+
42
+ **Local, single-user, unauthenticated.** helios-mcp acts with the credentials in your
43
+ own Helios settings (`helios.toml`, `HELIOS_*` variables). It serves nothing over the
44
+ network and checks no identity: anything that can launch it on your machine can use your
45
+ warehouse credentials through it. It is for one developer and their own agent. Shared,
46
+ governed deployments, where many people ask and each must be checked, serve the same tools
47
+ through Daedalus, which runs each call as the real user.
48
+
49
+ ## Configure your agent
50
+
51
+ From your project (where `helios.toml` is), print the configuration for your agent:
52
+
53
+ ```sh
54
+ helios mcp --print-config claude-code # or cursor, goose, vibe
55
+ ```
56
+
57
+ It names this environment's own `helios` and your config file as absolute paths, so it
58
+ works whatever directory the agent starts the server in, without activating your
59
+ virtualenv. Add `--as USER` to run every query as USER (see "Whose credentials"). The
60
+ output for each agent looks like this, with your paths:
61
+
62
+ **Claude Code**: `.mcp.json` in the project (Claude Code asks you to approve a project
63
+ server once), or the same in one command:
64
+ `claude mcp add --transport stdio --scope project helios -- /path/to/.venv/bin/helios --config /path/to/project/helios.toml mcp`
65
+
66
+ ```json
67
+ {
68
+ "mcpServers": {
69
+ "helios": {
70
+ "type": "stdio",
71
+ "command": "/path/to/.venv/bin/helios",
72
+ "args": ["--config", "/path/to/project/helios.toml", "mcp"],
73
+ "env": {}
74
+ }
75
+ }
76
+ }
77
+ ```
78
+
79
+ **Cursor**: `.cursor/mcp.json` in the project, or `~/.cursor/mcp.json` for every project.
80
+
81
+ ```json
82
+ {
83
+ "mcpServers": {
84
+ "helios": {
85
+ "command": "/path/to/.venv/bin/helios",
86
+ "args": ["--config", "/path/to/project/helios.toml", "mcp"],
87
+ "env": {}
88
+ }
89
+ }
90
+ }
91
+ ```
92
+
93
+ **goose**: under `extensions` in `~/.config/goose/config.yaml`
94
+ (`%APPDATA%\Block\goose\config\config.yaml` on Windows).
95
+
96
+ ```yaml
97
+ extensions:
98
+ helios:
99
+ name: helios
100
+ type: stdio
101
+ enabled: true
102
+ cmd: /path/to/.venv/bin/helios
103
+ args: [--config, /path/to/project/helios.toml, mcp]
104
+ envs: {}
105
+ timeout: 300
106
+ ```
107
+
108
+ **Mistral Vibe**: `.vibe/config.toml` in the project, or `~/.vibe/config.toml`. Vibe
109
+ shows the tools as `helios_list_models`, `helios_run_query` and so on.
110
+
111
+ ```toml
112
+ [[mcp_servers]]
113
+ name = "helios"
114
+ transport = "stdio"
115
+ command = "/path/to/.venv/bin/helios"
116
+ args = ["--config", "/path/to/project/helios.toml", "mcp"]
117
+ ```
118
+
119
+ Any other MCP client that launches a stdio server takes the same command and arguments.
120
+ A token for a `token` connection is never written into these files: set
121
+ `HELIOS_CALLER_TOKEN` in the agent's environment (its `env`, `envs`, or your shell).
122
+
123
+ ## What it serves
124
+
125
+ Every tool in helios-serve's registry: `list_models`, `describe_model`,
126
+ `search_semantics`, `describe`, `compile_query`, `run_query`, and `explain_lineage` when
127
+ a catalog with lineage is installed (helios-cloudera's Atlas). Names, descriptions and
128
+ input schemas are the registry's; every tool is marked `readOnlyHint` (none changes
129
+ data). Arguments are checked against the schema before a tool runs, and a tool's error
130
+ (`invalid_semantic_query`, `model_not_found`, ...) comes back as an error result with a
131
+ message the agent can act on.
132
+
133
+ ## Whose credentials
134
+
135
+ By default, yours: queries run with the credentials of the connection in your settings
136
+ (its `service` identity), so `helios mcp` works on a laptop with DuckDB. To have the
137
+ warehouse enforce someone's permissions instead, run it as them: `helios mcp --as USER`
138
+ (an `impersonate` connection), or set `HELIOS_CALLER_TOKEN` for a `token` connection.
139
+ A `service` connection then refuses, since it cannot run a query as anyone but itself.
140
+
141
+ ## Which configuration
142
+
143
+ The same as the `Helios` facade and every `helios` command: `HELIOS_CONFIG`, else
144
+ `./helios.toml`, else `[tool.helios]` in `./pyproject.toml`, under the `HELIOS_*`
145
+ variables. Relative paths in the file are relative to the file, so an agent that starts
146
+ `helios mcp` in your project (Claude Code does) or anywhere with
147
+ `HELIOS_CONFIG=/path/to/project/helios.toml` sees the models your programs see. A DuckDB
148
+ warehouse is opened read-only, so the agent, a notebook and a harvest can use it at once.
149
+
150
+ Status: Phase 7 of `docs/helios-decomposition-burndown.md` is done: the package and
151
+ command (7.1), the tools (7.2), the shared configuration (7.3), the tests on the sample
152
+ model (7.4) and this guide (7.5).
@@ -0,0 +1,124 @@
1
+ # helios-mcp
2
+
3
+ The Helios tools over MCP on stdio, for one developer's local agent: Claude Code,
4
+ Cursor, goose, Mistral Vibe or any other MCP client.
5
+
6
+ ```sh
7
+ pip install helios-mcp
8
+ helios mcp --help
9
+ ```
10
+
11
+ You don't run `helios mcp` by hand: your agent launches it and talks to it over its
12
+ stdin and stdout.
13
+
14
+ **Local, single-user, unauthenticated.** helios-mcp acts with the credentials in your
15
+ own Helios settings (`helios.toml`, `HELIOS_*` variables). It serves nothing over the
16
+ network and checks no identity: anything that can launch it on your machine can use your
17
+ warehouse credentials through it. It is for one developer and their own agent. Shared,
18
+ governed deployments, where many people ask and each must be checked, serve the same tools
19
+ through Daedalus, which runs each call as the real user.
20
+
21
+ ## Configure your agent
22
+
23
+ From your project (where `helios.toml` is), print the configuration for your agent:
24
+
25
+ ```sh
26
+ helios mcp --print-config claude-code # or cursor, goose, vibe
27
+ ```
28
+
29
+ It names this environment's own `helios` and your config file as absolute paths, so it
30
+ works whatever directory the agent starts the server in, without activating your
31
+ virtualenv. Add `--as USER` to run every query as USER (see "Whose credentials"). The
32
+ output for each agent looks like this, with your paths:
33
+
34
+ **Claude Code**: `.mcp.json` in the project (Claude Code asks you to approve a project
35
+ server once), or the same in one command:
36
+ `claude mcp add --transport stdio --scope project helios -- /path/to/.venv/bin/helios --config /path/to/project/helios.toml mcp`
37
+
38
+ ```json
39
+ {
40
+ "mcpServers": {
41
+ "helios": {
42
+ "type": "stdio",
43
+ "command": "/path/to/.venv/bin/helios",
44
+ "args": ["--config", "/path/to/project/helios.toml", "mcp"],
45
+ "env": {}
46
+ }
47
+ }
48
+ }
49
+ ```
50
+
51
+ **Cursor**: `.cursor/mcp.json` in the project, or `~/.cursor/mcp.json` for every project.
52
+
53
+ ```json
54
+ {
55
+ "mcpServers": {
56
+ "helios": {
57
+ "command": "/path/to/.venv/bin/helios",
58
+ "args": ["--config", "/path/to/project/helios.toml", "mcp"],
59
+ "env": {}
60
+ }
61
+ }
62
+ }
63
+ ```
64
+
65
+ **goose**: under `extensions` in `~/.config/goose/config.yaml`
66
+ (`%APPDATA%\Block\goose\config\config.yaml` on Windows).
67
+
68
+ ```yaml
69
+ extensions:
70
+ helios:
71
+ name: helios
72
+ type: stdio
73
+ enabled: true
74
+ cmd: /path/to/.venv/bin/helios
75
+ args: [--config, /path/to/project/helios.toml, mcp]
76
+ envs: {}
77
+ timeout: 300
78
+ ```
79
+
80
+ **Mistral Vibe**: `.vibe/config.toml` in the project, or `~/.vibe/config.toml`. Vibe
81
+ shows the tools as `helios_list_models`, `helios_run_query` and so on.
82
+
83
+ ```toml
84
+ [[mcp_servers]]
85
+ name = "helios"
86
+ transport = "stdio"
87
+ command = "/path/to/.venv/bin/helios"
88
+ args = ["--config", "/path/to/project/helios.toml", "mcp"]
89
+ ```
90
+
91
+ Any other MCP client that launches a stdio server takes the same command and arguments.
92
+ A token for a `token` connection is never written into these files: set
93
+ `HELIOS_CALLER_TOKEN` in the agent's environment (its `env`, `envs`, or your shell).
94
+
95
+ ## What it serves
96
+
97
+ Every tool in helios-serve's registry: `list_models`, `describe_model`,
98
+ `search_semantics`, `describe`, `compile_query`, `run_query`, and `explain_lineage` when
99
+ a catalog with lineage is installed (helios-cloudera's Atlas). Names, descriptions and
100
+ input schemas are the registry's; every tool is marked `readOnlyHint` (none changes
101
+ data). Arguments are checked against the schema before a tool runs, and a tool's error
102
+ (`invalid_semantic_query`, `model_not_found`, ...) comes back as an error result with a
103
+ message the agent can act on.
104
+
105
+ ## Whose credentials
106
+
107
+ By default, yours: queries run with the credentials of the connection in your settings
108
+ (its `service` identity), so `helios mcp` works on a laptop with DuckDB. To have the
109
+ warehouse enforce someone's permissions instead, run it as them: `helios mcp --as USER`
110
+ (an `impersonate` connection), or set `HELIOS_CALLER_TOKEN` for a `token` connection.
111
+ A `service` connection then refuses, since it cannot run a query as anyone but itself.
112
+
113
+ ## Which configuration
114
+
115
+ The same as the `Helios` facade and every `helios` command: `HELIOS_CONFIG`, else
116
+ `./helios.toml`, else `[tool.helios]` in `./pyproject.toml`, under the `HELIOS_*`
117
+ variables. Relative paths in the file are relative to the file, so an agent that starts
118
+ `helios mcp` in your project (Claude Code does) or anywhere with
119
+ `HELIOS_CONFIG=/path/to/project/helios.toml` sees the models your programs see. A DuckDB
120
+ warehouse is opened read-only, so the agent, a notebook and a harvest can use it at once.
121
+
122
+ Status: Phase 7 of `docs/helios-decomposition-burndown.md` is done: the package and
123
+ command (7.1), the tools (7.2), the shared configuration (7.3), the tests on the sample
124
+ model (7.4) and this guide (7.5).
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "helios-mcp"
7
+ version = "0.3.0"
8
+ description = "Helios tools over MCP on stdio, for one developer's local agent (Claude Code, Cursor, goose, Mistral Vibe)"
9
+ readme = "README.md"
10
+ authors = [{name = "Helios Team"}]
11
+ license = "Apache-2.0"
12
+ requires-python = ">=3.11"
13
+ keywords = ["mcp", "model context protocol", "semantic layer", "text-to-sql", "agents"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Database",
24
+ "Typing :: Typed",
25
+ ]
26
+ # helios-serve's tools and the MCP SDK. Local and single-user: no HTTP, no
27
+ # authentication, no deployment (decision 8); shared deployments use Daedalus.
28
+ dependencies = [
29
+ "helios-serve>=0.3.0",
30
+ "jsonschema>=4.23.0", # checks each call's arguments against the tool's input schema
31
+ "mcp>=2.2.0,<3",
32
+ "pyyaml>=6.0.0", # goose's configuration snippet
33
+ ]
34
+
35
+ # helios mcp: serve the tools over stdio.
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/christopheraburns/helios"
39
+ Documentation = "https://github.com/christopheraburns/helios/tree/main/packages/helios-mcp#readme"
40
+ Repository = "https://github.com/christopheraburns/helios"
41
+ Issues = "https://github.com/christopheraburns/helios/issues"
42
+
43
+ [project.entry-points."helios.commands"]
44
+ mcp = "helios_mcp.commands:McpCommand"
45
+
46
+ [tool.hatch.build.targets.wheel]
47
+ packages = ["src/helios_mcp"]
@@ -0,0 +1,28 @@
1
+ """helios-mcp: the Helios tools over MCP on stdio, for one developer's local agent
2
+ (burndown Phase 7).
3
+
4
+ ``helios mcp`` starts it; an agent launches that command and talks to it over its stdin
5
+ and stdout. It is local, single-user and unauthenticated: it acts with the credentials in
6
+ your Helios settings, and serves nothing over the network. Shared, governed deployments
7
+ serve the same tools through Daedalus.
8
+ """
9
+
10
+ _EXPORTS = {"build_server": "server", "serve_stdio": "server", "SERVER_NAME": "server"}
11
+
12
+ __all__ = sorted(_EXPORTS)
13
+
14
+
15
+ def __getattr__(name: str):
16
+ # Exports are imported on first use, so importing helios_mcp loads neither the MCP SDK nor any tool.
17
+ if name in _EXPORTS:
18
+ from importlib import import_module
19
+
20
+ return getattr(import_module(f"helios_mcp.{_EXPORTS[name]}"), name)
21
+ if name == "__version__":
22
+ from importlib.metadata import PackageNotFoundError, version
23
+
24
+ try:
25
+ return version("helios-mcp")
26
+ except PackageNotFoundError: # running from a source path without an install
27
+ return "0.0.0+unknown"
28
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,73 @@
1
+ """Configuration snippets that make a local agent launch ``helios mcp``
2
+ (``helios mcp --print-config AGENT``).
3
+
4
+ Each snippet names this environment's own ``helios`` (an absolute path, since an agent
5
+ does not activate your virtualenv) and an absolute ``--config``, so it works whatever
6
+ directory the agent starts the server in. Nothing secret is written: a caller token
7
+ stays in ``HELIOS_CALLER_TOKEN``, which you set in the agent's environment yourself.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ SERVER = "helios"
16
+ AGENTS = {
17
+ "claude-code": "Claude Code: .mcp.json in the project (or `claude mcp add`)",
18
+ "cursor": "Cursor: .cursor/mcp.json in the project, or ~/.cursor/mcp.json",
19
+ "goose": "goose: under extensions in ~/.config/goose/config.yaml",
20
+ "vibe": "Mistral Vibe: .vibe/config.toml in the project, or ~/.vibe/config.toml",
21
+ }
22
+
23
+
24
+ def launch(config: Path, caller: str | None = None) -> tuple[str, list[str]]:
25
+ """The command and arguments that start ``helios mcp`` with ``config``: the ``helios``
26
+ script beside this interpreter when there is one, else this interpreter running it."""
27
+ script = Path(sys.executable).with_name("helios")
28
+ command, prefix = (str(script), []) if script.is_file() else (sys.executable, ["-m", "helios_cortex.cli"])
29
+ args = [*prefix, "--config", str(config), "mcp"]
30
+ if caller:
31
+ args += ["--as", caller]
32
+ return command, args
33
+
34
+
35
+ def snippet(agent: str, command: str, args: list[str]) -> str:
36
+ """The configuration ``agent`` reads, for one stdio server named ``helios``."""
37
+ if agent == "claude-code":
38
+ return json.dumps({"mcpServers": {SERVER: {"type": "stdio", "command": command, "args": args, "env": {}}}},
39
+ indent=2)
40
+ if agent == "cursor":
41
+ return json.dumps({"mcpServers": {SERVER: {"command": command, "args": args, "env": {}}}}, indent=2)
42
+ if agent == "goose":
43
+ import yaml
44
+
45
+ return yaml.safe_dump({"extensions": {SERVER: {
46
+ "name": SERVER, "type": "stdio", "enabled": True, "cmd": command, "args": args, "envs": {},
47
+ "timeout": 300}}}, sort_keys=False)
48
+ if agent == "vibe":
49
+ # TOML basic strings take JSON's escapes, so json.dumps quotes paths safely.
50
+ return "\n".join(["[[mcp_servers]]", f"name = {json.dumps(SERVER)}", 'transport = "stdio"',
51
+ f"command = {json.dumps(command)}", f"args = {json.dumps(args)}", ""])
52
+ raise ValueError(f"unknown agent {agent!r}; one of {', '.join(AGENTS)}")
53
+
54
+
55
+ def server_entry(agent: str, text: str) -> tuple[str, list[str], dict[str, str]]:
56
+ """Read a snippet back as an agent would: the command, arguments and environment it
57
+ launches the ``helios`` server with."""
58
+ if agent in ("claude-code", "cursor"):
59
+ entry = json.loads(text)["mcpServers"][SERVER]
60
+ return entry["command"], entry["args"], entry.get("env") or {}
61
+ if agent == "goose":
62
+ import yaml
63
+
64
+ entry = yaml.safe_load(text)["extensions"][SERVER]
65
+ assert entry["type"] == "stdio" and entry["enabled"]
66
+ return entry["cmd"], entry["args"], entry.get("envs") or {}
67
+ if agent == "vibe":
68
+ import tomllib
69
+
70
+ [entry] = [e for e in tomllib.loads(text)["mcp_servers"] if e["name"] == SERVER]
71
+ assert entry["transport"] == "stdio"
72
+ return entry["command"], entry["args"], entry.get("env") or {}
73
+ raise ValueError(f"unknown agent {agent!r}")
@@ -0,0 +1,67 @@
1
+ """``helios mcp``: serve the Helios tools over stdio to a local agent (helios.commands)."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING
7
+
8
+ from helios_cortex.cli import CommandError, add_caller_argument
9
+
10
+ if TYPE_CHECKING:
11
+ from helios_cortex.cli import CommandContext
12
+
13
+
14
+ class McpCommand:
15
+ help = "serve the Helios tools over MCP on stdio, for a local agent (single-user, unauthenticated)"
16
+
17
+ def configure(self, parser: argparse.ArgumentParser) -> None:
18
+ parser.description = (
19
+ "Serve the Helios tools over MCP on stdin and stdout. An agent (Claude Code, Cursor, goose, "
20
+ "Mistral Vibe) launches this command itself; you do not run it by hand. It is local, single-user "
21
+ "and unauthenticated, acting with the credentials in your Helios settings; shared deployments "
22
+ "serve the tools through Daedalus.")
23
+ add_caller_argument(parser, "run every query")
24
+ from helios_mcp.agents import AGENTS
25
+
26
+ parser.add_argument("--print-config", choices=sorted(AGENTS), metavar="AGENT",
27
+ help="print the configuration that makes AGENT launch this server, with this "
28
+ "environment's helios and config file as absolute paths, and exit: "
29
+ + "; ".join(AGENTS.values()))
30
+
31
+ def run(self, args: argparse.Namespace, context: CommandContext) -> int:
32
+ if args.print_config:
33
+ from helios_mcp.agents import launch, snippet
34
+
35
+ command, launch_args = launch(_config_file(context), args.caller)
36
+ context.echo(snippet(args.print_config, command, launch_args).rstrip("\n"))
37
+ return 0
38
+ # Stdout is the protocol: nothing may be echoed. The helios command logs to stderr.
39
+ from helios_serve import Stores, single_user_policy
40
+
41
+ from helios_mcp.server import build_server, serve_stdio
42
+
43
+ caller = context.caller(args.caller)
44
+ # No caller: this user, with the connections' own (service) credentials, so the
45
+ # single-user policy lets those run. A caller (--as, or HELIOS_CALLER_TOKEN for token
46
+ # mode): the default policy, so the warehouse enforces that caller.
47
+ overrides = {} if caller is not None else {"data_policy": single_user_policy()}
48
+ serve_stdio(build_server(Stores.from_settings(context.settings, **overrides), caller=caller))
49
+ return 0
50
+
51
+
52
+ def _config_file(context: CommandContext) -> Path:
53
+ """The config file this command reads (``--config``, ``HELIOS_CONFIG``, ``./helios.toml``,
54
+ ``./pyproject.toml``), as an absolute path for the agent's configuration."""
55
+ from helios_cortex.settings import config_file
56
+
57
+ found = Path(context.config) if context.config else config_file()
58
+ if found is None:
59
+ raise CommandError("no helios.toml here: run `helios init`, or pass --config FILE")
60
+ if not found.is_file():
61
+ raise CommandError(f"Helios config file not found: {found}")
62
+ if found.name == "pyproject.toml":
63
+ import tomllib
64
+
65
+ if "helios" not in tomllib.loads(found.read_text()).get("tool", {}):
66
+ raise CommandError(f"{found} has no [tool.helios]: run `helios init`, or pass --config FILE")
67
+ return found.resolve()
File without changes
@@ -0,0 +1,127 @@
1
+ """The MCP server: ``build_server(stores, caller=...)`` makes it, ``serve_stdio(server)``
2
+ runs it on this process's stdin and stdout until the agent closes them.
3
+
4
+ Every tool in helios-serve's registry is offered with the registry's name, description
5
+ and input schema; ``readOnlyHint`` comes from its ``effect`` (no Helios tool changes
6
+ data, so it is set on all of them). A call's arguments are checked against the schema
7
+ before the tool runs; the tool's result is the call's structured content (and its JSON
8
+ text), and a result with an ``error`` is an error result the agent can read and correct.
9
+ Nothing here listens on a network.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import logging
15
+ from typing import TYPE_CHECKING, Any
16
+
17
+ if TYPE_CHECKING:
18
+ from helios_cortex.caller import Caller
19
+ from helios_serve import Registry, Stores, Tool
20
+ from mcp.server import Server
21
+
22
+ LOGGER = logging.getLogger(__name__)
23
+
24
+ SERVER_NAME = "helios"
25
+ INSTRUCTIONS = (
26
+ "Helios answers questions about data from published semantic models: list the models, search their "
27
+ "datasets, fields and metrics, compile metrics and dimensions to SQL, and run it on the warehouse. "
28
+ "Call search_semantics before compiling or running a query and copy names exactly from its results. "
29
+ "This server is local and single-user: it acts with the credentials in this user's Helios settings.")
30
+
31
+
32
+ # The MCP hints for each registry effect. Neither changes data: ``read`` reads Helios's
33
+ # metadata and ``query`` runs SELECTs on the warehouse. An effect with no entry here (a
34
+ # future one that writes) fails at startup rather than being offered as read-only.
35
+ HINTS = {
36
+ "read": {"read_only_hint": True, "destructive_hint": False, "idempotent_hint": True, "open_world_hint": False},
37
+ "query": {"read_only_hint": True, "destructive_hint": False, "idempotent_hint": True, "open_world_hint": False},
38
+ }
39
+
40
+
41
+ def annotations_for(entry: Tool):
42
+ """The MCP hints for a registry tool, from its ``effect``."""
43
+ import mcp_types as types
44
+
45
+ return types.ToolAnnotations(**HINTS[entry.effect.value])
46
+
47
+
48
+ def mcp_tool(entry: Tool):
49
+ import mcp_types as types
50
+
51
+ return types.Tool(name=entry.name, description=entry.description, input_schema=entry.input_schema,
52
+ annotations=annotations_for(entry))
53
+
54
+
55
+ def _result(payload: dict[str, Any]):
56
+ import mcp_types as types
57
+
58
+ payload = json.loads(json.dumps(payload, default=str)) # JSON as it stands, whatever a tool returned
59
+ return types.CallToolResult(content=[types.TextContent(type="text", text=json.dumps(payload))],
60
+ structured_content=payload, is_error=bool(payload.get("error")))
61
+
62
+
63
+ def _refused(code: str, message: str):
64
+ return _result({"error": code, "message": message, "retryable": False})
65
+
66
+
67
+ def _argument_problem(entry: Tool, arguments: dict[str, Any]) -> str | None:
68
+ from jsonschema import Draft202012Validator
69
+
70
+ errors = sorted(Draft202012Validator(entry.input_schema).iter_errors(arguments), key=lambda e: list(e.path))
71
+ if not errors:
72
+ return None
73
+ first = errors[0]
74
+ where = ".".join(str(p) for p in first.path)
75
+ return f"{where}: {first.message}" if where else first.message
76
+
77
+
78
+ def build_server(stores: Stores, *, caller: Caller | None = None, registry: Registry | None = None) -> Server:
79
+ """The ``helios`` MCP server offering ``registry``'s tools (default: every installed
80
+ one) on ``stores``, each call made as ``caller`` (None: the connections' own service
81
+ identity, this user's credentials)."""
82
+ import anyio
83
+ import mcp_types as types
84
+ from helios_serve import load_registry
85
+ from mcp.server import Server
86
+
87
+ import helios_mcp
88
+
89
+ registry = registry if registry is not None else load_registry()
90
+ listed = types.ListToolsResult(tools=[mcp_tool(entry) for entry in registry.tools()])
91
+
92
+ async def list_tools(ctx, params):
93
+ return listed
94
+
95
+ async def call_tool(ctx, params: types.CallToolRequestParams):
96
+ entry = registry.get(params.name)
97
+ if entry is None:
98
+ return _refused("unknown_tool", f"there is no tool named {params.name!r}; list the tools to see them")
99
+ arguments = dict(params.arguments or {})
100
+ problem = _argument_problem(entry, arguments)
101
+ if problem:
102
+ return _refused("invalid_tool_arguments", f"{params.name}: {problem}")
103
+ try:
104
+ result = await anyio.to_thread.run_sync(lambda: entry(caller, stores, **arguments))
105
+ except Exception as exc: # the tool logged it; the agent gets no internals
106
+ LOGGER.warning("tool %s raised %s", params.name, type(exc).__name__)
107
+ return _result({"error": "tool_failed", "message": f"{params.name} failed; see the server's log",
108
+ "retryable": True})
109
+ return _result(result if isinstance(result, dict) else {"result": result})
110
+
111
+ return Server(SERVER_NAME, version=helios_mcp.__version__, title="Helios", instructions=INSTRUCTIONS,
112
+ on_list_tools=list_tools, on_call_tool=call_tool)
113
+
114
+
115
+ async def _serve(server: Server) -> None:
116
+ from mcp.server.stdio import stdio_server
117
+
118
+ async with stdio_server() as (read_stream, write_stream):
119
+ await server.run(read_stream, write_stream, server.create_initialization_options())
120
+
121
+
122
+ def serve_stdio(server: Server) -> None:
123
+ """Serve ``server`` on stdin and stdout until they close. Stdout carries the protocol,
124
+ so anything else this process prints must go to stderr."""
125
+ import anyio
126
+
127
+ anyio.run(_serve, server)
@@ -0,0 +1,95 @@
1
+ """A DuckDB warehouse with helios-serve's published shop model, as Stores and as a
2
+ helios.toml (for `helios mcp` in a subprocess)."""
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import duckdb
7
+ import pytest
8
+
9
+ from helios_cortex.artifacts import ArtifactStore
10
+ from helios_cortex.domain import DataSource, DataSourceReference, Model
11
+ from helios_cortex.ossie import dump_yaml
12
+ from helios_cortex.registry import SqlRegistry
13
+ from helios_cortex.settings import Settings
14
+
15
+ SHOP = json.loads((Path(__file__).resolve().parents[2] / "helios-serve/tests/fixtures/shop.ossie.json").read_text())
16
+
17
+
18
+ @pytest.fixture
19
+ def config(tmp_path):
20
+ """helios.toml for a DuckDB warehouse whose shop model is registered and published."""
21
+ warehouse = tmp_path / "warehouse.duckdb"
22
+ with duckdb.connect(str(warehouse)) as db:
23
+ db.execute("CREATE SCHEMA shop")
24
+ db.execute("CREATE TABLE shop.customers AS SELECT i AS c_customer_id, "
25
+ "CASE WHEN i % 2 = 0 THEN 'east' ELSE 'west' END AS c_region FROM range(1, 21) t(i)")
26
+ db.execute("CREATE TABLE shop.orders AS SELECT i AS o_order_id, 1 + i % 20 AS o_customer_id, "
27
+ "i * 1.5 AS o_amount FROM range(1, 101) t(i)")
28
+ path = tmp_path / "helios.toml"
29
+ path.write_text(f'data_dir = "{tmp_path / "data"}"\n\n[connections.default]\nengine = "duckdb"\n'
30
+ f'path = "{warehouse}"\n')
31
+ settings = Settings.from_file(path)
32
+ registry = SqlRegistry.from_settings(settings)
33
+ registry.save_data_source(DataSource("warehouse", "Warehouse", "duckdb", "default"))
34
+ registry.save_model(Model("shop", "Shop", (DataSourceReference("warehouse"),)), status="published")
35
+ ArtifactStore.from_settings(settings).write_published_ossie("shop", SHOP, dump_yaml(SHOP), {"run_id": "r1"})
36
+ return path
37
+
38
+
39
+ @pytest.fixture
40
+ def stores(config):
41
+ from helios_serve import Stores, single_user_policy
42
+
43
+ return Stores.from_settings(Settings.from_file(config), data_policy=single_user_policy())
44
+
45
+
46
+ REPO = Path(__file__).resolve().parents[3]
47
+ TPCDS_TYPES = {"bigint": "BIGINT", "int": "INTEGER", "string": "VARCHAR", "date": "DATE"}
48
+
49
+
50
+ @pytest.fixture(scope="module")
51
+ def tpcds_warehouse(tmp_path_factory):
52
+ """The TPC-DS sample in DuckDB: the trimmed star of helios-cortex's harvest fixture with
53
+ generated rows (store sales by date, item and store)."""
54
+ import random
55
+
56
+ harvest = json.loads((REPO / "packages/helios-cortex/tests/fixtures/tpcds-harvest.json").read_text())
57
+ path = tmp_path_factory.mktemp("tpcds") / "warehouse.duckdb"
58
+ random.seed(11)
59
+ with duckdb.connect(str(path)) as db:
60
+ db.execute("CREATE SCHEMA tpcds")
61
+ for table in harvest["tables"]:
62
+ if table["table"] in {"store_sales", "item", "date_dim", "store"}:
63
+ columns = ", ".join(f"{c['name']} {TPCDS_TYPES.get(c['type'].split('(')[0], c['type'].upper())}"
64
+ for c in table["columns"])
65
+ db.execute(f"CREATE TABLE tpcds.{table['table']} ({columns})")
66
+ db.execute("INSERT INTO tpcds.date_dim (d_date_sk, d_year, d_moy) "
67
+ "SELECT i, 1998 + (i // 12), 1 + (i % 12) FROM range(1, 61) t(i)")
68
+ db.execute("INSERT INTO tpcds.item (i_item_sk, i_brand) SELECT i, 'brand' || (i % 7) FROM range(1, 31) t(i)")
69
+ db.execute("INSERT INTO tpcds.store (s_store_sk, s_state) "
70
+ "SELECT i, ['TX','TN','SD'][1 + (i % 3)] FROM range(1, 7) t(i)")
71
+ db.executemany("INSERT INTO tpcds.store_sales (ss_sold_date_sk, ss_item_sk, ss_store_sk, ss_quantity, "
72
+ "ss_net_paid) VALUES (?, ?, ?, ?, ?)",
73
+ [(random.randint(1, 60), random.randint(1, 30), random.randint(1, 6), random.randint(1, 5),
74
+ round(random.uniform(1, 90), 2)) for _ in range(1000)])
75
+ return path
76
+
77
+
78
+ @pytest.fixture
79
+ def tpcds_config(tmp_path, tpcds_warehouse):
80
+ """A project helios.toml for the TPC-DS sample, its model registered and published."""
81
+ from helios_cortex.ossie import SemanticModel
82
+
83
+ project = tmp_path / "project"
84
+ project.mkdir()
85
+ path = project / "helios.toml"
86
+ path.write_text(f'data_dir = "helios-data"\n\n[connections.default]\nengine = "duckdb"\n'
87
+ f'path = "{tpcds_warehouse}"\n')
88
+ settings = Settings.from_file(path)
89
+ registry = SqlRegistry.from_settings(settings)
90
+ registry.save_data_source(DataSource("warehouse", "TPC-DS sample", "duckdb", "default"))
91
+ registry.save_model(Model("tpcds", "TPC-DS", (DataSourceReference("warehouse"),)), status="published")
92
+ document = SemanticModel.load(str(REPO / "models/published/tpcds.ossie.yaml")).doc
93
+ ArtifactStore.from_settings(settings).write_published_ossie("tpcds", document, dump_yaml(document),
94
+ {"run_id": "sample"})
95
+ return path
@@ -0,0 +1,63 @@
1
+ """helios-mcp is a package of its own (burndown 7.1): helios-serve, jsonschema and the MCP SDK, a
2
+ `helios mcp` subcommand, and a server an MCP client can initialize, in process and over
3
+ real stdio."""
4
+ import json
5
+ import subprocess
6
+ import sys
7
+ import tomllib
8
+ from importlib.metadata import requires
9
+ from pathlib import Path
10
+
11
+ import anyio
12
+ from mcp import Client
13
+ from mcp.client.stdio import StdioServerParameters
14
+
15
+ import helios_mcp
16
+ from helios_mcp import SERVER_NAME, build_server
17
+
18
+ PACKAGE = Path(__file__).resolve().parents[1]
19
+
20
+
21
+ def test_the_package_reports_its_version_and_depends_on_serve_and_the_sdk():
22
+ project = tomllib.loads((PACKAGE / "pyproject.toml").read_text())["project"]
23
+ assert helios_mcp.__version__ == project["version"]
24
+ installed = {r.split(";")[0].split("[")[0].split(">")[0].split("=")[0].split("<")[0].strip().lower()
25
+ for r in requires("helios-mcp") or []}
26
+ assert installed == {"helios-serve", "jsonschema", "mcp", "pyyaml"}
27
+
28
+
29
+ def test_importing_it_loads_no_sdk_no_web_server_and_no_other_helios_package():
30
+ probe = ("import json, sys, helios_mcp; "
31
+ "print(json.dumps(sorted({m.partition('.')[0] for m in sys.modules})))")
32
+ loaded = set(json.loads(subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True,
33
+ check=True).stdout))
34
+ assert not loaded & {"mcp", "apps", "uvicorn", "fastapi", "helios_model", "helios_cloudera", "helios_semantic"}
35
+
36
+
37
+ def test_helios_mcp_is_a_subcommand():
38
+ listed = subprocess.run([sys.executable, "-m", "helios_cortex.cli", "--help"], capture_output=True, text=True)
39
+ assert listed.returncode == 0 and "mcp" in listed.stdout
40
+ described = subprocess.run([sys.executable, "-m", "helios_cortex.cli", "mcp", "--help"], capture_output=True,
41
+ text=True)
42
+ assert described.returncode == 0
43
+ assert "single-user" in described.stdout and "Daedalus" in described.stdout
44
+
45
+
46
+ async def _initialize(server):
47
+ async with Client(server) as client:
48
+ return client.server_info, client.instructions
49
+
50
+
51
+ def test_an_mcp_client_initializes_the_server_in_process(stores):
52
+ info, instructions = anyio.run(_initialize, build_server(stores))
53
+ assert (info.name, info.version, info.title) == (SERVER_NAME, helios_mcp.__version__, "Helios")
54
+ assert "search_semantics" in instructions and "single-user" in instructions
55
+
56
+
57
+ def test_an_agent_launches_helios_mcp_over_stdio(tmp_path):
58
+ """What Claude Code or goose does: run the command and speak MCP on its stdin/stdout."""
59
+ (tmp_path / "helios.toml").write_text(f'data_dir = "{tmp_path / "data"}"\n')
60
+ launch = StdioServerParameters(command=sys.executable, args=["-m", "helios_cortex.cli", "-q", "mcp"],
61
+ cwd=str(tmp_path))
62
+ info, _ = anyio.run(_initialize, launch)
63
+ assert (info.name, info.version) == ("helios", helios_mcp.__version__)
@@ -0,0 +1,105 @@
1
+ """The sample model over MCP (burndown 7.4, 7.5 and the Phase 7 gate): an in-process MCP
2
+ client lists the tools and runs compile_query and run_query on the TPC-DS sample; and each
3
+ agent's configuration from `helios mcp --print-config`, read back and launched exactly as
4
+ that agent would, lists the tools and answers the same query. Answers are checked against
5
+ SQL written by hand on the same DuckDB file."""
6
+ import subprocess
7
+ import sys
8
+
9
+ import anyio
10
+ import duckdb
11
+ import pytest
12
+ from mcp import Client
13
+ from mcp.client.stdio import StdioServerParameters
14
+
15
+ from helios_cortex.settings import Settings
16
+ from helios_serve import Stores, load_registry, single_user_policy
17
+ from helios_mcp import build_server
18
+ from helios_mcp.agents import AGENTS, server_entry
19
+
20
+ BY_YEAR = {"metrics": ["Store Sales Revenue", "Store Sales Quantity"], "dimensions": ["tpcds.date_dim.d_year"]}
21
+ HAND = ("SELECT d.d_year, SUM(s.ss_net_paid), SUM(s.ss_quantity) FROM tpcds.store_sales s "
22
+ "JOIN tpcds.date_dim d ON s.ss_sold_date_sk = d.d_date_sk GROUP BY 1")
23
+
24
+
25
+ def expected(warehouse):
26
+ with duckdb.connect(str(warehouse), read_only=True) as db:
27
+ return sorted([year, str(revenue), quantity] for year, revenue, quantity in db.execute(HAND).fetchall())
28
+
29
+
30
+ def ask(server):
31
+ async def run():
32
+ async with Client(server) as client:
33
+ tools = (await client.list_tools()).tools
34
+ compiled = await client.call_tool("compile_query", BY_YEAR)
35
+ trino = await client.call_tool("compile_query", {**BY_YEAR, "dialect": "trino"})
36
+ ran = await client.call_tool("run_query", BY_YEAR)
37
+ return tools, compiled, trino, ran
38
+
39
+ return anyio.run(run)
40
+
41
+
42
+ def test_an_in_process_client_compiles_and_runs_on_the_sample(tpcds_config, tpcds_warehouse):
43
+ stores = Stores.from_settings(Settings.from_file(tpcds_config), data_policy=single_user_policy())
44
+ tools, compiled, trino, ran = ask(build_server(stores))
45
+ assert {t.name for t in tools} == set(load_registry())
46
+ assert not any(r.is_error for r in (compiled, trino, ran))
47
+ assert compiled.structured_content["dialect"] == "duckdb" and trino.structured_content["dialect"] == "trino"
48
+ assert compiled.structured_content["dataset"] == "tpcds.store_sales"
49
+ assert compiled.structured_content["joins"] == ["tpcds.date_dim"]
50
+ assert ran.structured_content["sql"] == compiled.structured_content["sql"]
51
+ assert sorted(ran.structured_content["rows"]) == expected(tpcds_warehouse)
52
+
53
+
54
+ def print_config(config, agent, *extra, cwd):
55
+ return subprocess.run([sys.executable, "-m", "helios_cortex.cli", "--config", str(config), "mcp",
56
+ "--print-config", agent, *extra], cwd=cwd, capture_output=True, text=True, check=True)
57
+
58
+
59
+ @pytest.mark.parametrize("agent", sorted(AGENTS))
60
+ def test_each_agents_configuration_launches_a_server_that_answers(agent, tpcds_config, tpcds_warehouse, tmp_path):
61
+ """The gate: an agent configured with the printed snippet, started in another directory."""
62
+ elsewhere = tmp_path / "agent-cwd"
63
+ elsewhere.mkdir()
64
+ printed = print_config(tpcds_config.relative_to(tmp_path), agent, cwd=tmp_path).stdout
65
+ command, args, env = server_entry(agent, printed)
66
+ assert str(tpcds_config) in args # absolute, wherever it was printed
67
+ launch = StdioServerParameters(command=command, args=args, env=env or None, cwd=str(elsewhere))
68
+ tools, _, _, ran = ask(launch)
69
+ assert {t.name for t in tools} == set(load_registry())
70
+ assert not ran.is_error and sorted(ran.structured_content["rows"]) == expected(tpcds_warehouse)
71
+ assert list(elsewhere.iterdir()) == [] # nothing written where the agent runs
72
+
73
+
74
+ def test_a_snippet_carries_the_caller_but_never_a_token(tpcds_config, tmp_path, monkeypatch):
75
+ monkeypatch.setenv("HELIOS_CALLER_TOKEN", "a-secret-jwt")
76
+ printed = print_config(tpcds_config, "claude-code", "--as", "alice", cwd=tmp_path).stdout
77
+ command, args, env = server_entry("claude-code", printed)
78
+ assert args[-2:] == ["--as", "alice"] and env == {}
79
+ assert "a-secret-jwt" not in printed
80
+
81
+
82
+ def test_print_config_needs_a_config_file(tmp_path):
83
+ missing = subprocess.run([sys.executable, "-m", "helios_cortex.cli", "mcp", "--print-config", "cursor"],
84
+ cwd=tmp_path, capture_output=True, text=True)
85
+ assert missing.returncode == 1 and "helios init" in missing.stderr
86
+ (tmp_path / "pyproject.toml").write_text('[project]\nname = "x"\n')
87
+ unrelated = subprocess.run([sys.executable, "-m", "helios_cortex.cli", "mcp", "--print-config", "cursor"],
88
+ cwd=tmp_path, capture_output=True, text=True)
89
+ assert unrelated.returncode == 1 and "[tool.helios]" in unrelated.stderr
90
+
91
+
92
+ def test_the_readmes_snippets_are_what_print_config_prints():
93
+ """The guide's four examples parse as each agent reads them and match --print-config's shape."""
94
+ import re
95
+ from pathlib import Path
96
+
97
+ from helios_mcp.agents import snippet
98
+
99
+ readme = (Path(__file__).resolve().parents[1] / "README.md").read_text()
100
+ blocks = dict(zip(("claude-code", "cursor", "goose", "vibe"),
101
+ re.findall(r"```(?:json|yaml|toml)\n(.*?)```", readme, re.S)))
102
+ command, args = "/path/to/.venv/bin/helios", ["--config", "/path/to/project/helios.toml", "mcp"]
103
+ for agent, text in blocks.items():
104
+ assert server_entry(agent, text) == server_entry(agent, snippet(agent, command, args)) == (command, args, {})
105
+ assert set(blocks) == set(AGENTS)
@@ -0,0 +1,122 @@
1
+ """Every registry tool over MCP (burndown 7.2): names, descriptions and input schemas from
2
+ the registry, readOnlyHint from the effect, arguments checked against the schema, tool
3
+ errors as error results, and the caller: this user's own credentials by default, or a
4
+ caller whom the warehouse must enforce. In process through the SDK's Client, and over
5
+ real stdio through `helios mcp`."""
6
+ import sys
7
+
8
+ import anyio
9
+ import pytest
10
+ from mcp import Client
11
+ from mcp.client.stdio import StdioServerParameters
12
+
13
+ from helios_cortex import Caller
14
+ from helios_serve import load_registry
15
+ from helios_mcp import build_server
16
+ from helios_mcp.server import HINTS
17
+
18
+
19
+ def session(server, *calls):
20
+ """List the tools, then make each (name, arguments) call; returns (tools, results)."""
21
+ async def run():
22
+ async with Client(server) as client:
23
+ listed = await client.list_tools()
24
+ return listed.tools, [await client.call_tool(name, arguments) for name, arguments in calls]
25
+
26
+ return anyio.run(run)
27
+
28
+
29
+ def test_every_registry_tool_is_offered_as_the_registry_describes_it(stores):
30
+ registry = load_registry()
31
+ tools, _ = session(build_server(stores))
32
+ assert [t.name for t in tools] == list(registry)
33
+ for offered in tools:
34
+ entry = registry[offered.name]
35
+ assert offered.description == entry.description
36
+ assert offered.input_schema == entry.input_schema
37
+ assert offered.annotations.read_only_hint is True and offered.annotations.destructive_hint is False
38
+
39
+
40
+ def test_every_effect_has_hints_and_none_writes():
41
+ from helios_serve.registry import Effect
42
+
43
+ assert set(HINTS) == {effect.value for effect in Effect}
44
+ assert all(hints["read_only_hint"] and not hints["destructive_hint"] for hints in HINTS.values())
45
+
46
+
47
+ def test_the_tools_answer_from_the_published_model(stores):
48
+ _, (models, search, compiled, ran) = session(
49
+ build_server(stores),
50
+ ("list_models", {}),
51
+ ("search_semantics", {"question": "revenue by region"}),
52
+ ("compile_query", {"metrics": ["revenue"], "dimensions": ["shop.customers.c_region"]}),
53
+ ("run_query", {"metrics": ["revenue"], "dimensions": ["shop.customers.c_region"],
54
+ "filters": [{"column": "shop.customers.c_region", "op": "=", "value": "east"}]}))
55
+ assert not any(r.is_error for r in (models, search, compiled, ran))
56
+ assert models.structured_content == {"models": [{"name": "shop", "status": "published"}]}
57
+ assert search.structured_content["matches"][0]["name"] == "revenue"
58
+ assert compiled.structured_content["dialect"] == "duckdb"
59
+ assert ran.structured_content["rows"] == [["east", "3750.0"]]
60
+ assert '"rows"' in ran.content[0].text # the same JSON, as text
61
+
62
+
63
+ def test_a_tool_error_is_an_error_result_the_agent_can_read(stores):
64
+ _, (unknown_metric, unknown_model) = session(
65
+ build_server(stores), ("run_query", {"metrics": ["profit"]}), ("describe_model", {"model": "nowhere"}))
66
+ assert unknown_metric.is_error and unknown_metric.structured_content["error"] == "invalid_semantic_query"
67
+ assert "search_semantics" in unknown_metric.structured_content["message"]
68
+ assert unknown_model.is_error and unknown_model.structured_content["error"] == "model_not_found"
69
+
70
+
71
+ @pytest.mark.parametrize(("name", "arguments", "code", "says"), [
72
+ ("run_query", {"metrics": "revenue"}, "invalid_tool_arguments", "metrics"), # a string, not a list
73
+ ("run_query", {}, "invalid_tool_arguments", "'metrics' is a required property"),
74
+ ("run_query", {"metrics": ["revenue"], "sql": "DROP TABLE x"}, "invalid_tool_arguments", "sql"),
75
+ ("run_query", {"metrics": ["revenue"], "filters": [{"column": "x"}]}, "invalid_tool_arguments", "op"),
76
+ ("run_query", {"metrics": ["revenue"], "limit": "ten"}, "invalid_tool_arguments", "limit"),
77
+ ("drop_table", {}, "unknown_tool", "drop_table"),
78
+ ])
79
+ def test_arguments_are_checked_against_the_schema_before_the_tool_runs(stores, name, arguments, code, says):
80
+ _, (result,) = session(build_server(stores), (name, arguments))
81
+ assert result.is_error and result.structured_content["error"] == code
82
+ assert says in result.structured_content["message"]
83
+
84
+
85
+ def test_a_raising_tool_says_so_without_internals(stores):
86
+ class Broken:
87
+ def sources(self):
88
+ raise RuntimeError("/secret/path is gone")
89
+
90
+ stores.models = Broken()
91
+ _, (result,) = session(build_server(stores), ("list_models", {}))
92
+ assert result.is_error and result.structured_content["error"] == "tool_failed"
93
+ assert "secret" not in result.content[0].text
94
+
95
+
96
+ def test_a_caller_is_left_to_the_warehouse(stores):
97
+ """A caller other than this user: the default policy, and DuckDB cannot run a query as alice."""
98
+ from helios_cortex.data_authorization import DataPolicy
99
+
100
+ stores.data_policy = DataPolicy()
101
+ _, (as_alice,) = session(build_server(stores, caller=Caller("alice")), ("run_query", {"metrics": ["revenue"]}))
102
+ assert as_alice.is_error and as_alice.structured_content["error"] == "data_authorization_denied"
103
+
104
+
105
+ def stdio(config, *args, env=None):
106
+ return StdioServerParameters(command=sys.executable, args=["-m", "helios_cortex.cli", "-q", "--config",
107
+ str(config), "mcp", *args],
108
+ cwd=str(config.parent), env=env)
109
+
110
+
111
+ def test_helios_mcp_serves_the_tools_over_stdio(config):
112
+ tools, (ran,) = session(stdio(config), ("run_query", {"metrics": ["revenue", "order_count"]}))
113
+ assert {t.name for t in tools} == set(load_registry())
114
+ assert not ran.is_error and ran.structured_content["rows"] == [["7575.0", 100]]
115
+
116
+
117
+ def test_helios_mcp_as_a_caller_lets_the_warehouse_decide(config):
118
+ _, (as_alice,) = session(stdio(config, "--as", "alice"), ("run_query", {"metrics": ["revenue"]}))
119
+ assert as_alice.structured_content["error"] == "data_authorization_denied"
120
+ _, (with_token,) = session(stdio(config, env={"HELIOS_CALLER_TOKEN": "a-jwt"}),
121
+ ("run_query", {"metrics": ["revenue"]}))
122
+ assert with_token.structured_content["error"] == "data_authorization_denied" # a service connection