streamwright-mcp 0.0.1__py3-none-any.whl

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,5 @@
1
+ """
2
+ StreamWright Model Context Protocol (MCP) Server.
3
+ """
4
+
5
+ __version__ = "0.1.0"
@@ -0,0 +1,26 @@
1
+ """
2
+ CLI entry point for StreamWright MCP server.
3
+ """
4
+
5
+ import argparse
6
+ import sys
7
+ from streamwright_mcp.server import server
8
+
9
+
10
+ def main(argv=None) -> None:
11
+ parser = argparse.ArgumentParser(
12
+ description="StreamWright Model Context Protocol (MCP) server."
13
+ )
14
+ parser.add_argument(
15
+ "--transport",
16
+ choices=["stdio", "sse", "streamable-http"],
17
+ default="stdio",
18
+ help="MCP transport protocol (default: stdio)",
19
+ )
20
+ args = parser.parse_args(argv)
21
+
22
+ server.run(transport=args.transport)
23
+
24
+
25
+ if __name__ == "__main__":
26
+ main()
@@ -0,0 +1,217 @@
1
+ """
2
+ Dynamic reflection and in-code contract inspection for StreamWright connectors.
3
+
4
+ Zero duplication: extracts contracts, schemas, auth specifications, and execution
5
+ behaviors directly from live Python connector modules and core schema definitions.
6
+ """
7
+
8
+ import importlib
9
+ import importlib.metadata
10
+ import inspect
11
+ from typing import Any, Dict, List, Optional
12
+
13
+ from streamwright.core.validation import schema as core_schema
14
+ from streamwright_mcp.hub import fetch_hub_connector, list_hub_connectors
15
+
16
+
17
+ def list_installed_connectors() -> List[Dict[str, Any]]:
18
+ """
19
+ Discovers all StreamWright connectors installed in the current Python environment
20
+ using the 'streamwright.connectors' entry points group.
21
+ """
22
+ eps = importlib.metadata.entry_points()
23
+ if hasattr(eps, "select"):
24
+ group = eps.select(group="streamwright.connectors")
25
+ else:
26
+ group = eps.get("streamwright.connectors", [])
27
+
28
+ results = []
29
+ seen = set()
30
+
31
+ for ep in group:
32
+ if ep.name in seen:
33
+ continue
34
+ seen.add(ep.name)
35
+
36
+ try:
37
+ cls = ep.load()
38
+ spec = getattr(cls, "spec", None)
39
+ dist = getattr(ep, "dist", None)
40
+ version = dist.version if dist else None
41
+
42
+ results.append({
43
+ "name": ep.name,
44
+ "title": getattr(spec, "title", ep.name.replace("_", " ").title()) if spec else ep.name,
45
+ "category": getattr(spec, "category", "general") if spec else "general",
46
+ "transport": getattr(spec, "transport", "unknown") if spec else "unknown",
47
+ "version": version,
48
+ "installed": True,
49
+ })
50
+ except Exception as exc:
51
+ results.append({
52
+ "name": ep.name,
53
+ "title": ep.name,
54
+ "category": "error",
55
+ "transport": "unknown",
56
+ "version": None,
57
+ "installed": False,
58
+ "error": str(exc),
59
+ })
60
+
61
+ results.sort(key=lambda x: x["name"])
62
+ return results
63
+
64
+
65
+ def get_connector_contract(name: str) -> Dict[str, Any]:
66
+ """
67
+ Retrieves the complete in-code contract for a connector.
68
+
69
+ If the connector is installed, extracts its 5-part contract from module/class docstrings,
70
+ its ConnectorSpec, auth schemas, and supported methods.
71
+ If not installed, returns Hub installation instructions.
72
+ """
73
+ eps = importlib.metadata.entry_points()
74
+ if hasattr(eps, "select"):
75
+ group = eps.select(group="streamwright.connectors")
76
+ else:
77
+ group = eps.get("streamwright.connectors", [])
78
+
79
+ matching_ep = None
80
+ for ep in group:
81
+ if ep.name == name:
82
+ matching_ep = ep
83
+ break
84
+
85
+ if matching_ep is not None:
86
+ try:
87
+ cls = matching_ep.load()
88
+ spec = getattr(cls, "spec", None)
89
+ mod = importlib.import_module(cls.__module__)
90
+ module_doc = inspect.getdoc(mod) or ""
91
+ class_doc = inspect.getdoc(cls) or ""
92
+
93
+ spec_info = {}
94
+ if spec:
95
+ spec_info = {
96
+ "name": getattr(spec, "name", name),
97
+ "title": getattr(spec, "title", name),
98
+ "category": getattr(spec, "category", None),
99
+ "transport": getattr(spec, "transport", None),
100
+ "extension": getattr(spec, "extension", None),
101
+ "package": getattr(spec, "package", None),
102
+ }
103
+
104
+ auth_required = getattr(cls, "auth_required", ())
105
+ auth_optional = getattr(cls, "auth_optional", ())
106
+ services = getattr(mod, "SERVICES", None) or getattr(cls, "SERVICES", None)
107
+ default_service = getattr(mod, "DEFAULT_SERVICE", None) or getattr(cls, "DEFAULT_SERVICE", None)
108
+
109
+ # Build full contract documentation
110
+ contract_doc = module_doc if module_doc else class_doc
111
+
112
+ return {
113
+ "name": name,
114
+ "installed": True,
115
+ "spec": spec_info,
116
+ "auth": {
117
+ "required_fields": list(auth_required) if isinstance(auth_required, (list, tuple)) else auth_required,
118
+ "optional_fields": list(auth_optional) if isinstance(auth_optional, (list, tuple)) else auth_optional,
119
+ },
120
+ "services": services,
121
+ "default_service": default_service,
122
+ "contract_documentation": contract_doc,
123
+ }
124
+ except Exception as exc:
125
+ return {
126
+ "name": name,
127
+ "installed": False,
128
+ "error": f"Failed to load installed connector: {exc}",
129
+ }
130
+
131
+ # Not installed: look up in StreamWright Hub
132
+ hub_data = fetch_hub_connector(name)
133
+ install_cmd = f"pip install streamwright-{name.replace('_', '-')}"
134
+ if hub_data and "install" in hub_data and isinstance(hub_data["install"], dict):
135
+ git_target = hub_data["install"].get("git")
136
+ if git_target:
137
+ install_cmd = f"pip install \"{git_target}\""
138
+
139
+ return {
140
+ "name": name,
141
+ "installed": False,
142
+ "message": f"Connector '{name}' is not installed in the current Python environment.",
143
+ "install_command": install_cmd,
144
+ "hub_metadata": hub_data or {
145
+ "title": name.replace("_", " ").title(),
146
+ "install_hint": install_cmd,
147
+ },
148
+ }
149
+
150
+
151
+ def get_core_schema(kind: str = "all") -> Dict[str, Any]:
152
+ """
153
+ Returns the formal JSON schema and DSL documentation for StreamWright sources and streams.
154
+
155
+ Args:
156
+ kind: 'source', 'stream', or 'all' (default).
157
+ """
158
+ result: Dict[str, Any] = {
159
+ "version": core_schema.VERSION,
160
+ "supported_versions": list(core_schema.SUPPORTED_VERSIONS),
161
+ "kind": kind,
162
+ }
163
+
164
+ if kind in ("source", "all"):
165
+ result["source_schema"] = core_schema.json_schema()
166
+ if kind in ("stream", "all"):
167
+ result["stream_schema"] = core_schema.stream_json_schema()
168
+ if kind == "all":
169
+ result["dsl_specification"] = inspect.getdoc(core_schema) or ""
170
+
171
+ return result
172
+
173
+
174
+ def get_cli_reference(command: Optional[str] = None) -> Dict[str, Any]:
175
+ """
176
+ Guides the AI assistant on how to inspect, discover, and execute StreamWright CLI commands.
177
+ Directs the LLM to run or inspect the live CLI help directly in the user's terminal/workspace.
178
+
179
+ Args:
180
+ command: Optional subcommand to inspect ('run', 'validate', 'connectors', 'mcp').
181
+ """
182
+ subcommand = (command or "").strip().lower()
183
+
184
+ if subcommand in ("run", "validate", "connectors", "mcp"):
185
+ return {
186
+ "binary": "streamwright",
187
+ "alias": "sw",
188
+ "command": subcommand,
189
+ "instruction": f"To get the most accurate and up-to-date options for '{subcommand}', inspect the CLI directly by running or checking: `sw {subcommand} --help` (or `streamwright {subcommand} --help`).",
190
+ "recommended_command": f"sw {subcommand} --help",
191
+ "fallback_command": f"python -m streamwright.core.cli {subcommand} --help",
192
+ "summary": {
193
+ "run": "Executes a pipeline source and exports records to Singer, JSONL, Parquet, DuckDB, or dlt.",
194
+ "validate": "Statically validates source and stream YAML configurations, refs, and DuckDB SQL.",
195
+ "connectors": "Lists installed connectors or searches/installs connectors from the StreamWright Hub.",
196
+ "mcp": "Runs the StreamWright Model Context Protocol server for AI coding assistants.",
197
+ }.get(subcommand, ""),
198
+ }
199
+
200
+ return {
201
+ "binary": "streamwright",
202
+ "alias": "sw",
203
+ "invocation_notes": "Both 'sw' and 'streamwright' are completely interchangeable.",
204
+ "instruction": "To discover all commands and live options, ask the user's terminal to inspect: `sw --help` (or `streamwright --help`). For specific subcommands, run `sw <command> --help`.",
205
+ "recommended_command": "sw --help",
206
+ "fallback_command": "python -m streamwright.core.cli --help",
207
+ "available_subcommands": {
208
+ "run": "sw run --help",
209
+ "validate": "sw validate --help",
210
+ "connectors": "sw connectors --help",
211
+ "mcp": "sw mcp --help",
212
+ },
213
+ }
214
+
215
+
216
+
217
+
@@ -0,0 +1,90 @@
1
+ """
2
+ StreamWright Hub client for connector discovery.
3
+
4
+ Used strictly as a fallback to discover connectors that are not installed locally.
5
+ Does not cache to disk (no ~/.streamwright/connectors.json) and does not store auth or schema details.
6
+ """
7
+
8
+ import logging
9
+ from typing import Any, Dict, List, Optional
10
+ import requests
11
+ import yaml
12
+
13
+ LOG = logging.getLogger("streamwright_mcp.hub")
14
+
15
+ HUB_RAW_BASE = "https://raw.githubusercontent.com/karthick-jaganathan/streamwright-hub/main/connectors"
16
+ HUB_INDEX_URL = "https://api.github.com/repos/karthick-jaganathan/streamwright-hub/contents/connectors"
17
+
18
+ # Known official connectors for offline discovery fallback
19
+ KNOWN_HUB_CONNECTORS = [
20
+ "restapi", "files", "s3", "gcs", "azure_blob", "postgres",
21
+ "mysql", "mongodb", "deltalake", "google_ads", "microsoft_ads",
22
+ "meta_ads", "openai_ads", "linkedin_ads", "amazon_ads", "apple_ads",
23
+ ]
24
+
25
+ _MEM_CACHE: Dict[str, Dict[str, Any]] = {}
26
+
27
+
28
+ def fetch_hub_connector(name: str, timeout: float = 3.0) -> Optional[Dict[str, Any]]:
29
+ """
30
+ Fetches connector metadata from the StreamWright Hub repository.
31
+ Returns None if unreachable or not found.
32
+ """
33
+ if name in _MEM_CACHE:
34
+ return _MEM_CACHE[name]
35
+
36
+ url = f"{HUB_RAW_BASE}/{name}.yaml"
37
+ try:
38
+ resp = requests.get(url, timeout=timeout)
39
+ if resp.status_code == 200:
40
+ data = yaml.safe_load(resp.text)
41
+ if isinstance(data, dict):
42
+ _MEM_CACHE[name] = data
43
+ return data
44
+ except Exception as exc:
45
+ LOG.debug("Failed to fetch connector %s from hub: %s", name, exc)
46
+
47
+ return None
48
+
49
+
50
+ def list_hub_connectors(timeout: float = 3.0) -> List[Dict[str, Any]]:
51
+ """
52
+ Lists available connectors from the StreamWright Hub registry.
53
+ """
54
+ connectors = []
55
+ # Try fetching directory listing from GitHub API
56
+ try:
57
+ resp = requests.get(HUB_INDEX_URL, timeout=timeout)
58
+ if resp.status_code == 200:
59
+ items = resp.json()
60
+ for item in items:
61
+ name = item.get("name", "")
62
+ if name.endswith(".yaml"):
63
+ conn_name = name[:-5]
64
+ conn_data = fetch_hub_connector(conn_name, timeout=timeout)
65
+ if conn_data:
66
+ connectors.append(conn_data)
67
+ else:
68
+ connectors.append({
69
+ "key": conn_name,
70
+ "title": conn_name.replace("_", " ").title(),
71
+ "install_hint": f"pip install streamwright-{conn_name.replace('_', '-')}"
72
+ })
73
+ if connectors:
74
+ return connectors
75
+ except Exception as exc:
76
+ LOG.debug("Failed to list connectors from GitHub API: %s", exc)
77
+
78
+ # Fallback to known list
79
+ for name in KNOWN_HUB_CONNECTORS:
80
+ conn_data = fetch_hub_connector(name, timeout=timeout)
81
+ if conn_data:
82
+ connectors.append(conn_data)
83
+ else:
84
+ connectors.append({
85
+ "key": name,
86
+ "title": name.replace("_", " ").title(),
87
+ "install_hint": f"pip install streamwright-{name.replace('_', '-')}"
88
+ })
89
+
90
+ return connectors
@@ -0,0 +1,170 @@
1
+ """
2
+ Stream transformation and SQL inspection engine for StreamWright MCP.
3
+
4
+ Analyzes pipeline stream configurations, requests, DuckDB SQL transform steps,
5
+ and export definitions.
6
+ """
7
+
8
+ import os
9
+ import re
10
+ from typing import Any, Dict, List, Optional
11
+
12
+ from streamwright.core.config.loader import load_source
13
+
14
+ _TABLE_REF = re.compile(r"\bFROM\s+([A-Za-z_][A-Za-z0-9_]*)\b|\bJOIN\s+([A-Za-z_][A-Za-z0-9_]*)\b", re.IGNORECASE)
15
+
16
+
17
+ def _extract_sql_sources(sql: str) -> List[str]:
18
+ """Extracts table names referenced in FROM or JOIN clauses."""
19
+ sources = set()
20
+ for match in _TABLE_REF.finditer(sql):
21
+ t1, t2 = match.groups()
22
+ table = t1 or t2
23
+ if table:
24
+ sources.add(table)
25
+ return sorted(list(sources))
26
+
27
+
28
+ def inspect_stream_transform(source_dir: str, stream_name: str) -> Dict[str, Any]:
29
+ """
30
+ Parses and inspects a specific stream's requests, SQL transformations, and exports.
31
+
32
+ Args:
33
+ source_dir: Absolute or relative path to the source directory.
34
+ stream_name: Name of the stream to inspect.
35
+
36
+ Returns:
37
+ Structured breakdown of the stream's execution plan.
38
+ """
39
+ abs_path = os.path.abspath(os.path.expanduser(source_dir))
40
+ if not os.path.exists(abs_path):
41
+ return {
42
+ "found": False,
43
+ "error": f"Source directory '{source_dir}' does not exist.",
44
+ }
45
+
46
+ try:
47
+ source_data = load_source(abs_path)
48
+ except Exception as exc:
49
+ return {
50
+ "found": False,
51
+ "error": f"Failed to load source at '{source_dir}': {exc}",
52
+ }
53
+
54
+ streams = source_data.get("streams", [])
55
+ matched_stream: Optional[Dict[str, Any]] = None
56
+ all_stream_names = []
57
+
58
+ for s in streams:
59
+ name = s.get("name")
60
+ if name:
61
+ all_stream_names.append(name)
62
+ if name == stream_name:
63
+ matched_stream = s
64
+
65
+ if not matched_stream:
66
+ return {
67
+ "found": False,
68
+ "stream_name": stream_name,
69
+ "error": f"Stream '{stream_name}' not found in source '{abs_path}'.",
70
+ "available_streams": all_stream_names,
71
+ }
72
+
73
+ # Analyze requests
74
+ raw_requests = matched_stream.get("requests", [])
75
+ parsed_requests = []
76
+ request_names = set()
77
+ for req in raw_requests:
78
+ req_name = req.get("name")
79
+ if req_name:
80
+ request_names.add(req_name)
81
+ if "http" in req:
82
+ http_spec = req.get("http", {})
83
+ parsed_requests.append({
84
+ "name": req_name,
85
+ "kind": "http",
86
+ "method": http_spec.get("method", "GET"),
87
+ "path": http_spec.get("path"),
88
+ "params": http_spec.get("params"),
89
+ })
90
+ elif "sdk" in req:
91
+ parsed_requests.append({
92
+ "name": req_name,
93
+ "kind": "sdk",
94
+ "sdk": req.get("sdk"),
95
+ "service": req.get("service"),
96
+ "method": req.get("method"),
97
+ "arguments": req.get("arguments"),
98
+ })
99
+ else:
100
+ parsed_requests.append({
101
+ "name": req_name,
102
+ "kind": "custom",
103
+ "spec": req,
104
+ })
105
+
106
+ # Analyze transform steps
107
+ transform_block = matched_stream.get("transform", {})
108
+ mode = transform_block.get("mode", "page")
109
+ steps = transform_block.get("steps", [])
110
+
111
+ # If steps is not in transform dict (e.g. shorthand transform: [...])
112
+ if isinstance(transform_block, list):
113
+ steps = transform_block
114
+ mode = "page"
115
+
116
+ parsed_steps = []
117
+ for step in steps:
118
+ step_name = step.get("name")
119
+ select_sql = step.get("select", "").strip()
120
+ referenced_tables = _extract_sql_sources(select_sql)
121
+
122
+ # Distinguish whether input is a raw request table or intermediate step
123
+ inputs = []
124
+ for ref in referenced_tables:
125
+ if ref in request_names:
126
+ inputs.append({"name": ref, "type": "request"})
127
+ else:
128
+ inputs.append({"name": ref, "type": "step_or_table"})
129
+
130
+ parsed_steps.append({
131
+ "name": step_name,
132
+ "description": step.get("description"),
133
+ "select_sql": select_sql,
134
+ "inputs": inputs,
135
+ })
136
+
137
+ # Analyze exports
138
+ exports_block = matched_stream.get("export", {})
139
+ parsed_exports = []
140
+ if isinstance(exports_block, dict):
141
+ for exp_name, exp_cfg in exports_block.items():
142
+ if isinstance(exp_cfg, dict):
143
+ parsed_exports.append({
144
+ "name": exp_name,
145
+ "step": exp_cfg.get("step"),
146
+ "primary_key": exp_cfg.get("primary_key", []),
147
+ "description": exp_cfg.get("description"),
148
+ })
149
+ elif isinstance(exp_cfg, str):
150
+ parsed_exports.append({
151
+ "name": exp_name,
152
+ "step": exp_cfg,
153
+ "primary_key": [],
154
+ })
155
+
156
+ return {
157
+ "found": True,
158
+ "stream_name": stream_name,
159
+ "source_name": source_data.get("name"),
160
+ "description": matched_stream.get("description"),
161
+ "partitions": matched_stream.get("partitions"),
162
+ "incremental": matched_stream.get("incremental"),
163
+ "requests": parsed_requests,
164
+ "transform": {
165
+ "mode": mode,
166
+ "step_count": len(parsed_steps),
167
+ "steps": parsed_steps,
168
+ },
169
+ "exports": parsed_exports,
170
+ }
@@ -0,0 +1,153 @@
1
+ """
2
+ StreamWright Model Context Protocol (MCP) Server.
3
+
4
+ Exposes programmatic tools and resources for inspecting connector contracts,
5
+ core schemas, source validation, and transform analysis without file duplication.
6
+ """
7
+
8
+ import json
9
+ from typing import Any, Dict, List, Optional
10
+
11
+ try:
12
+ from mcp.server.mcpserver import MCPServer
13
+ except ImportError:
14
+ from mcp.server.fastmcp import FastMCP as MCPServer
15
+
16
+ from streamwright_mcp.contracts import (
17
+ get_cli_reference as _get_cli_reference,
18
+ get_connector_contract as _get_contract,
19
+ get_core_schema as _get_schema,
20
+ list_installed_connectors,
21
+ )
22
+ from streamwright_mcp.hub import list_hub_connectors
23
+ from streamwright_mcp.inspector import inspect_stream_transform as _inspect_transform
24
+ from streamwright_mcp.validator import validate_source_config as _validate_source
25
+
26
+ server = MCPServer("streamwright-mcp")
27
+
28
+
29
+ @server.tool()
30
+ def list_connectors(include_hub: bool = False) -> List[Dict[str, Any]]:
31
+ """
32
+ Lists StreamWright connectors.
33
+
34
+ Args:
35
+ include_hub: If True, also includes uninstalled connectors available in the StreamWright Hub registry.
36
+
37
+ Returns:
38
+ List of connector summaries containing name, title, category, transport, and installation status.
39
+ """
40
+ installed = list_installed_connectors()
41
+ if not include_hub:
42
+ return installed
43
+
44
+ installed_names = {c["name"] for c in installed}
45
+ hub_connectors = list_hub_connectors()
46
+
47
+ results = list(installed)
48
+ for h in hub_connectors:
49
+ key = h.get("key")
50
+ if key and key not in installed_names:
51
+ results.append({
52
+ "name": key,
53
+ "title": h.get("title", key.replace("_", " ").title()),
54
+ "category": h.get("family", "hub"),
55
+ "transport": "unknown",
56
+ "version": None,
57
+ "installed": False,
58
+ "install_hint": h.get("install_hint", f"pip install streamwright-{key.replace('_', '-')}"),
59
+ })
60
+
61
+ results.sort(key=lambda x: x["name"])
62
+ return results
63
+
64
+
65
+ @server.tool()
66
+ def get_connector_contract(name: str) -> Dict[str, Any]:
67
+ """
68
+ Retrieves the complete in-code contract for a StreamWright connector.
69
+
70
+ Returns the 5-part specification:
71
+ 1. source.yaml contract snippet
72
+ 2. streams/<stream>.yaml contract snippet
73
+ 3. Authentication & secrets requirements
74
+ 4. Transform & DuckDB SQL data shaping
75
+ 5. Execution & runtime behaviors (transport, pagination, retries)
76
+
77
+ If the connector is not installed locally, returns the installation command.
78
+
79
+ Args:
80
+ name: Name of the connector (e.g. 's3', 'postgres', 'restapi', 'google_ads', 'openai_ads').
81
+ """
82
+ return _get_contract(name)
83
+
84
+
85
+ @server.tool()
86
+ def get_core_schema(kind: str = "all") -> Dict[str, Any]:
87
+ """
88
+ Returns the formal Draft 7 JSON schema and declarative DSL specification for StreamWright.
89
+
90
+ Args:
91
+ kind: 'source' (source.yaml schema), 'stream' (streams/*.yaml schema), or 'all' (both schemas plus full DSL documentation).
92
+ """
93
+ return _get_schema(kind)
94
+
95
+
96
+ @server.tool()
97
+ def validate_source_config(source_dir: str) -> Dict[str, Any]:
98
+ """
99
+ Performs static validation on a StreamWright source folder (source.yaml and streams/*.yaml).
100
+
101
+ Checks YAML structure, keys, credentials, Jinja references, DuckDB SQL transforms,
102
+ and export consistency with pinpoint file:line diagnostics.
103
+
104
+ Args:
105
+ source_dir: Absolute or relative path to the source directory.
106
+ """
107
+ return _validate_source(source_dir)
108
+
109
+
110
+ @server.tool()
111
+ def inspect_stream_transform(source_dir: str, stream_name: str) -> Dict[str, Any]:
112
+ """
113
+ Parses and explains the requests, DuckDB SQL transform steps, table inputs,
114
+ and export contracts for a specific stream.
115
+
116
+ Args:
117
+ source_dir: Path to the pipeline source directory.
118
+ stream_name: Name of the stream to inspect.
119
+ """
120
+ return _inspect_transform(source_dir, stream_name)
121
+
122
+
123
+ @server.tool()
124
+ def get_cli_reference(command: Optional[str] = None) -> Dict[str, Any]:
125
+ """
126
+ Guides the AI assistant on how to inspect, discover, and run StreamWright CLI commands.
127
+ Directs the LLM to run and inspect `sw --help` or `sw <subcommand> --help` directly in the user's workspace.
128
+
129
+ Args:
130
+ command: Optional subcommand to inspect ('run', 'validate', 'connectors', 'mcp').
131
+ """
132
+ return _get_cli_reference(command)
133
+
134
+
135
+ # Resources
136
+ @server.resource("streamwright://schema/source")
137
+ def source_schema_resource() -> str:
138
+ """JSON Schema (Draft 7) for StreamWright source.yaml."""
139
+ schema_dict = _get_schema("source").get("source_schema", {})
140
+ return json.dumps(schema_dict, indent=2)
141
+
142
+
143
+ @server.resource("streamwright://schema/stream")
144
+ def stream_schema_resource() -> str:
145
+ """JSON Schema (Draft 7) for StreamWright streams/<stream>.yaml."""
146
+ schema_dict = _get_schema("stream").get("stream_schema", {})
147
+ return json.dumps(schema_dict, indent=2)
148
+
149
+
150
+ @server.resource("streamwright://schema/core")
151
+ def core_dsl_resource() -> str:
152
+ """Complete markdown specification contract of the StreamWright DSL."""
153
+ return _get_schema("all").get("dsl_specification", "")
@@ -0,0 +1,99 @@
1
+ """
2
+ Source configuration validation wrapper for StreamWright MCP.
3
+
4
+ Validates StreamWright source directories without executing them,
5
+ returning structured file-and-line diagnostics.
6
+ """
7
+
8
+ import os
9
+ from typing import Any, Dict, List
10
+
11
+ from streamwright.core.validation.engine import validate_source
12
+
13
+
14
+ def validate_source_config(source_dir: str) -> Dict[str, Any]:
15
+ """
16
+ Validates a StreamWright source folder (source.yaml and streams/*.yaml).
17
+
18
+ Args:
19
+ source_dir: Absolute or relative path to the source directory.
20
+
21
+ Returns:
22
+ Structured diagnostic dictionary with valid status, error count, warning count,
23
+ and list of issue items.
24
+ """
25
+ abs_path = os.path.abspath(os.path.expanduser(source_dir))
26
+ if not os.path.exists(abs_path):
27
+ return {
28
+ "valid": False,
29
+ "error_count": 1,
30
+ "warning_count": 0,
31
+ "errors": [{
32
+ "severity": "error",
33
+ "code": "not-found",
34
+ "message": f"Source directory '{source_dir}' does not exist.",
35
+ "file": source_dir,
36
+ "line": None,
37
+ "column": None,
38
+ "path": "",
39
+ }],
40
+ "warnings": [],
41
+ "summary": f"Failed: Directory '{source_dir}' does not exist.",
42
+ }
43
+
44
+ try:
45
+ issues = validate_source(abs_path)
46
+ except Exception as exc:
47
+ return {
48
+ "valid": False,
49
+ "error_count": 1,
50
+ "warning_count": 0,
51
+ "errors": [{
52
+ "severity": "error",
53
+ "code": "validator-exception",
54
+ "message": str(exc),
55
+ "file": source_dir,
56
+ "line": None,
57
+ "column": None,
58
+ "path": "",
59
+ }],
60
+ "warnings": [],
61
+ "summary": f"Validation failed with exception: {exc}",
62
+ }
63
+
64
+ errors: List[Dict[str, Any]] = []
65
+ warnings: List[Dict[str, Any]] = []
66
+
67
+ for issue in issues:
68
+ item = {
69
+ "severity": issue.severity,
70
+ "code": getattr(issue, "code", ""),
71
+ "message": issue.message,
72
+ "file": getattr(issue, "file", None),
73
+ "line": getattr(issue, "line", None),
74
+ "column": getattr(issue, "column", None),
75
+ "path": getattr(issue, "path", ""),
76
+ }
77
+ if issue.severity == "error":
78
+ errors.append(item)
79
+ else:
80
+ warnings.append(item)
81
+
82
+ is_valid = len(errors) == 0
83
+ if is_valid:
84
+ if len(warnings) == 0:
85
+ summary = f"Valid: Source '{os.path.basename(abs_path)}' has no errors or warnings."
86
+ else:
87
+ summary = f"Valid with warnings: Source '{os.path.basename(abs_path)}' has {len(warnings)} warning(s)."
88
+ else:
89
+ summary = f"Invalid: Source '{os.path.basename(abs_path)}' has {len(errors)} error(s) and {len(warnings)} warning(s)."
90
+
91
+ return {
92
+ "valid": is_valid,
93
+ "source_path": abs_path,
94
+ "error_count": len(errors),
95
+ "warning_count": len(warnings),
96
+ "errors": errors,
97
+ "warnings": warnings,
98
+ "summary": summary,
99
+ }
@@ -0,0 +1,153 @@
1
+ Metadata-Version: 2.4
2
+ Name: streamwright-mcp
3
+ Version: 0.0.1
4
+ Summary: Model Context Protocol (MCP) server for StreamWright declarative ELT framework
5
+ Author: Karthick Jaganathan
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://streamwright.web.app
8
+ Project-URL: Documentation, https://streamwright.web.app/docs/ai/mcp
9
+ Project-URL: Repository, https://github.com/karthick-jaganathan/streamwright-mcp
10
+ Project-URL: Issue Tracker, https://github.com/karthick-jaganathan/streamwright-mcp/issues
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: mcp>=1.0.0
15
+ Requires-Dist: streamwright>=0.1.0
16
+ Requires-Dist: pyyaml>=6.0.0
17
+ Requires-Dist: pydantic>=2.0.0
18
+ Requires-Dist: requests>=2.25.0
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest>=8.0.0; extra == "test"
21
+ Dynamic: license-file
22
+
23
+ # StreamWright MCP Server
24
+
25
+ [![PyPI version](https://img.shields.io/pypi/v/streamwright-mcp.svg)](https://pypi.org/project/streamwright-mcp/)
26
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
27
+ [![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
28
+
29
+ **StreamWright MCP** is the official [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server for [StreamWright](https://streamwright.web.app), the declarative data integration and ELT framework.
30
+
31
+ It allows AI coding assistants (such as Claude Desktop, Cursor, Google Antigravity, GitHub Copilot, and Zed) to inspect installed connectors, query Draft-7 pipeline schemas, validate YAML sources with pinpoint error locations, and analyze DuckDB SQL transform pipelines in real time — eliminating hallucinations when building data pipelines.
32
+
33
+ ---
34
+
35
+ ## Key Capabilities
36
+
37
+ - **In-Code Connector Contracts**: Introspects installed connector packages (`restapi`, `postgres`, `s3`, etc.) directly from Python entry points to extract live contracts, authentication specs, and transport behaviors without static copies.
38
+ - **Hub Discovery**: Discovers uninstalled connectors from the StreamWright Hub registry and provides instant installation recipes.
39
+ - **Static Pipeline Validation**: Validates `source.yaml` and `streams/*.yaml` pipelines before execution, returning structured diagnostics with file, line, and column locations.
40
+ - **SQL Transform Inspection**: Parses and traces multi-step DuckDB SQL transformations, table dependencies, and export formats for any stream.
41
+ - **Core DSL Schemas**: Exposes authoritative Draft-7 JSON schemas for editor autocomplete, linting, and LLM grounding.
42
+ - **CLI Guidance**: Steers AI agents to explore live CLI commands (`sw run`, `sw validate`, `sw connectors`, `sw mcp`) in the local workspace.
43
+
44
+ ---
45
+
46
+ ## Installation
47
+
48
+ Install via `pip`:
49
+
50
+ ```bash
51
+ pip install streamwright-mcp
52
+ ```
53
+
54
+ Or using `uv`:
55
+
56
+ ```bash
57
+ uv pip install streamwright-mcp
58
+ ```
59
+
60
+ ---
61
+
62
+ ## Configuration
63
+
64
+ Add `streamwright-mcp` to your MCP client configuration file (e.g., `claude_desktop_config.json`, `mcp.json`, or Antigravity's `mcp_config.json`).
65
+
66
+ ### Standard Configuration
67
+
68
+ ```json
69
+ {
70
+ "mcpServers": {
71
+ "streamwright": {
72
+ "command": "streamwright-mcp"
73
+ }
74
+ }
75
+ }
76
+ ```
77
+
78
+ ### Using StreamWright CLI Shorthand (`sw`)
79
+
80
+ If you have `streamwright` installed, you can launch the MCP server directly via `sw mcp`:
81
+
82
+ ```json
83
+ {
84
+ "mcpServers": {
85
+ "streamwright": {
86
+ "command": "sw",
87
+ "args": ["mcp"]
88
+ }
89
+ }
90
+ }
91
+ ```
92
+
93
+ ### Ephemeral Execution (`uvx`)
94
+
95
+ Run on-demand without installing into your global environment:
96
+
97
+ ```json
98
+ {
99
+ "mcpServers": {
100
+ "streamwright": {
101
+ "command": "uvx",
102
+ "args": ["streamwright-mcp"]
103
+ }
104
+ }
105
+ }
106
+ ```
107
+
108
+ ---
109
+
110
+ ## Usage
111
+
112
+ ### Starting the Server
113
+
114
+ The server runs over standard input/output (`stdio`) by default:
115
+
116
+ ```bash
117
+ streamwright-mcp
118
+ ```
119
+
120
+ You can also specify transport options:
121
+
122
+ ```bash
123
+ # stdio (default)
124
+ streamwright-mcp --transport stdio
125
+
126
+ # Server-Sent Events (SSE)
127
+ streamwright-mcp --transport sse
128
+ ```
129
+
130
+ Or run as a Python module:
131
+
132
+ ```bash
133
+ python -m streamwright_mcp.cli
134
+ ```
135
+
136
+ ---
137
+
138
+ ## Resources
139
+
140
+ MCP clients that support resource attachments can access:
141
+
142
+ - `streamwright://schema/source` — JSON Schema (Draft 7) for `source.yaml`.
143
+ - `streamwright://schema/stream` — JSON Schema (Draft 7) for `streams/<stream>.yaml`.
144
+ - `streamwright://schema/core` — Full Markdown specification of the StreamWright DSL.
145
+
146
+ ---
147
+
148
+ ## Documentation & Ecosystem
149
+
150
+ - **Documentation**: https://streamwright.web.app
151
+ - **MCP Guide**: https://streamwright.web.app/docs/ai/mcp
152
+ - **Core Package**: https://pypi.org/project/streamwright/
153
+ - **Repository**: https://github.com/karthick-jaganathan/streamwright-mcp
@@ -0,0 +1,13 @@
1
+ streamwright_mcp/__init__.py,sha256=4iy6InZKBEQcI0Sre-bWVxxmR0EmSU37nhEDBsQNb9c,81
2
+ streamwright_mcp/cli.py,sha256=mOTdnhrzyFuGqPMK-VKQegOG5LLhiHAXZVAkEVMdliY,576
3
+ streamwright_mcp/contracts.py,sha256=qQApBEycwH0NwmRZUNaXbQX58hoWo5amg7GIeAciY9k,8347
4
+ streamwright_mcp/hub.py,sha256=ldWZ5Tb9ZrZ-Cp82DNvy-7GUJl64qIPRrL7x9yjE2qw,3235
5
+ streamwright_mcp/inspector.py,sha256=hCZKYcDsSglds7azSQV8urBEQn19RQq8BKN1Q10LPWo,5536
6
+ streamwright_mcp/server.py,sha256=G0vE6kdZcmzCPjZXD4I-oXrdwfXpb5RMHJnTHHC6LKc,5170
7
+ streamwright_mcp/validator.py,sha256=FJDFr5FUiy0pnT_qHvGqueFB6V0g5Py-kT32FnYJ8ps,3157
8
+ streamwright_mcp-0.0.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
9
+ streamwright_mcp-0.0.1.dist-info/METADATA,sha256=t25SwHapgNWL7sHaLuYHhrUdK3JL0QrzTmD518ile0Y,4624
10
+ streamwright_mcp-0.0.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
11
+ streamwright_mcp-0.0.1.dist-info/entry_points.txt,sha256=LCT4J74-VDi5SUqiaWothyCTwALVnFP3VjQ_1MvtcTM,63
12
+ streamwright_mcp-0.0.1.dist-info/top_level.txt,sha256=S6_BYHDMgKEhYjH48h_PHmFjPCxN9BkzLX1fRhZKm1I,17
13
+ streamwright_mcp-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ streamwright-mcp = streamwright_mcp.cli:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ streamwright_mcp