artisan-es-reader-plugin 0.1.0__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,131 @@
1
+ Metadata-Version: 2.4
2
+ Name: artisan-es-reader-plugin
3
+ Version: 0.1.0
4
+ Summary: Elasticsearch MCP server — query logs with or without SSH tunnel
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: elasticsearch<9.0.0,>=8.0.0
7
+ Requires-Dist: mcp>=1.0.0
8
+ Requires-Dist: paramiko>=3.0.0
9
+ Requires-Dist: python-dotenv>=1.0.0
10
+ Requires-Dist: sshtunnel>=0.4.0
11
+ Description-Content-Type: text/markdown
12
+
13
+ # Elasticsearch MCP Server
14
+
15
+ Query Elasticsearch logs directly from Claude Cowork — with or without an SSH tunnel.
16
+
17
+ ---
18
+
19
+ ## Installation
20
+
21
+ ### 1. Install the plugin
22
+
23
+ Get **es-mcp** from the Cowork plugin marketplace and install it.
24
+
25
+ ### 2. Install `uv`
26
+
27
+ The MCP server runs via `uvx`, which requires `uv` to be installed on your machine:
28
+
29
+ ```powershell
30
+ # Windows
31
+ powershell -ExecutionPolicy Bypass -c "irm https://astral.sh/uv/install.ps1 | iex"
32
+ ```
33
+
34
+ ```bash
35
+ # macOS / Linux
36
+ curl -LsSf https://astral.sh/uv/install.sh | sh
37
+ ```
38
+
39
+ ### 3. Configure the MCP server
40
+
41
+ Open `claude_desktop_config.json`:
42
+
43
+ ```
44
+ Windows: %APPDATA%\Claude\claude_desktop_config.json
45
+ macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
46
+ ```
47
+
48
+ Add the entry inside `"mcpServers": { }`:
49
+
50
+ ```json
51
+ {
52
+ "mcpServers": {
53
+ "elasticsearch-logs": {
54
+ "command": "uvx",
55
+ "args": ["artisan-es-reader-plugin@latest", "artisan-es-reader-plugin"],
56
+ "env": {
57
+ "ES_HOST": "localhost",
58
+ "ES_PORT": "9200",
59
+ "ES_USERNAME": "your-es-username",
60
+ "ES_PASSWORD": "your-es-password",
61
+ "ES_USE_SSL": "true",
62
+ "ES_VERIFY_CERTS": "false",
63
+ "SSH_HOST": "your-bastion-ip",
64
+ "SSH_PORT": "22",
65
+ "SSH_USERNAME": "ubuntu",
66
+ "SSH_PEM_FILE": "C:\\Users\\your-name\\path\\to\\key.pem",
67
+ "SSH_REMOTE_ES_HOST": "localhost",
68
+ "SSH_REMOTE_ES_PORT": "9200",
69
+ "SSH_LOCAL_PORT": "0"
70
+ }
71
+ }
72
+ }
73
+ }
74
+ ```
75
+
76
+ Each team member only needs to fill in these personal values:
77
+
78
+ | Variable | Description |
79
+ |---|---|
80
+ | `ES_USERNAME` | Elasticsearch username |
81
+ | `ES_PASSWORD` | Elasticsearch password |
82
+ | `SSH_HOST` | Bastion / jump host IP or hostname |
83
+ | `SSH_PEM_FILE` | Absolute path to your local PEM key file |
84
+
85
+ > **Windows paths** must use double backslashes in JSON: `C:\\Users\\your-name\\key.pem`
86
+
87
+ ### 4. Restart Cowork
88
+
89
+ The SSH tunnel starts automatically on first tool use.
90
+
91
+ ---
92
+
93
+ ## Notes
94
+
95
+ - `ES_HOST` is only used for direct connections. When `SSH_HOST` is set, traffic routes through the tunnel and `ES_HOST` is ignored.
96
+ - `ES_USE_SSL`: set `true` if your Elasticsearch runs HTTPS.
97
+ - `ES_VERIFY_CERTS`: set `false` for self-signed certificates.
98
+ - `SSH_LOCAL_PORT`: `0` = auto-pick a free local port.
99
+ - To connect without SSH tunnel, leave `SSH_HOST` empty.
100
+
101
+ ---
102
+
103
+ ## Updating
104
+
105
+ ### For users
106
+
107
+ Updates are automatic — just restart Cowork and `uvx` will pull the latest version from PyPI.
108
+
109
+ ### For maintainers
110
+
111
+ 1. Make changes to `src/es_mcp/server.py`
112
+ 2. Bump the version in `pyproject.toml`
113
+ 3. Build and publish:
114
+ ```bash
115
+ python -m build
116
+ twine upload dist/*
117
+ ```
118
+ 4. Users get the new version automatically on next Cowork restart — no action needed on their end
119
+
120
+ ---
121
+
122
+ ## Available tools
123
+
124
+ | Tool | What it does |
125
+ |---|---|
126
+ | `list_indices` | List indices (supports glob pattern) |
127
+ | `search_logs` | Full-text search with filters, sort, pagination |
128
+ | `get_recent_errors` | Error-level entries from the last N minutes |
129
+ | `get_index_mapping` | Field schema for an index |
130
+ | `run_aggregation` | Run a custom ES aggregation |
131
+ | `connection_info` | Show active connection / tunnel status |
@@ -0,0 +1,6 @@
1
+ es_mcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ es_mcp/server.py,sha256=TAL70PaxShAbcXZlwAVkOF3EGNaBwCGsRkpoJD730y8,7847
3
+ artisan_es_reader_plugin-0.1.0.dist-info/METADATA,sha256=p2VbdMuqvWyEsXI2pZi17rvKVR5XWNRl-Oex2XqrEc0,3534
4
+ artisan_es_reader_plugin-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
5
+ artisan_es_reader_plugin-0.1.0.dist-info/entry_points.txt,sha256=oNtaqgb32hwPzBSIBQeTFTnSSK0acyee-9TuBbeapPM,64
6
+ artisan_es_reader_plugin-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ artisan-es-reader-plugin = es_mcp.server:main
es_mcp/__init__.py ADDED
File without changes
es_mcp/server.py ADDED
@@ -0,0 +1,255 @@
1
+ """
2
+ Elasticsearch MCP Server
3
+ Supports direct connection or SSH tunnel (PEM file).
4
+ """
5
+
6
+ import os
7
+ import json
8
+ import paramiko
9
+ from typing import Any
10
+
11
+ # sshtunnel references the removed paramiko.DSSKey in older versions — patch before import
12
+ if not hasattr(paramiko, "DSSKey"):
13
+ paramiko.DSSKey = type("DSSKey", (), {}) # type: ignore[attr-defined]
14
+
15
+ from dotenv import load_dotenv
16
+ from mcp.server.fastmcp import FastMCP
17
+ from elasticsearch import Elasticsearch
18
+ from sshtunnel import SSHTunnelForwarder
19
+
20
+ load_dotenv()
21
+
22
+ # ---------------------------------------------------------------------------
23
+ # SSH tunnel / ES client lifecycle
24
+ # ---------------------------------------------------------------------------
25
+
26
+ _tunnel: SSHTunnelForwarder | None = None
27
+ _es_client: Elasticsearch | None = None
28
+
29
+
30
+ def _build_es_client(host: str, port: int) -> Elasticsearch:
31
+ username = os.getenv("ES_USERNAME", "")
32
+ password = os.getenv("ES_PASSWORD", "")
33
+ use_ssl = os.getenv("ES_USE_SSL", "false").lower() == "true"
34
+ verify_certs = os.getenv("ES_VERIFY_CERTS", "false").lower() == "true"
35
+
36
+ scheme = "https" if use_ssl else "http"
37
+ kwargs: dict[str, Any] = {
38
+ "hosts": [{"host": host, "port": port, "scheme": scheme}],
39
+ "verify_certs": verify_certs,
40
+ }
41
+ if username and password:
42
+ kwargs["basic_auth"] = (username, password)
43
+
44
+ return Elasticsearch(**kwargs)
45
+
46
+
47
+ def _start_tunnel() -> tuple[SSHTunnelForwarder, int]:
48
+ pem_path = os.path.expanduser(os.getenv("SSH_PEM_FILE", "~/.ssh/id_rsa"))
49
+ ssh_host = os.getenv("SSH_HOST", "").strip().strip('"')
50
+ tunnel = SSHTunnelForwarder(
51
+ (ssh_host, int(os.getenv("SSH_PORT", "22"))),
52
+ ssh_username=os.getenv("SSH_USERNAME", "ubuntu"),
53
+ ssh_pkey=pem_path,
54
+ remote_bind_address=(
55
+ os.getenv("SSH_REMOTE_ES_HOST", "localhost"),
56
+ int(os.getenv("SSH_REMOTE_ES_PORT", "9200")),
57
+ ),
58
+ local_bind_address=("127.0.0.1", int(os.getenv("SSH_LOCAL_PORT", "0"))),
59
+ )
60
+ tunnel.start()
61
+ return tunnel, tunnel.local_bind_port
62
+
63
+
64
+ def get_es() -> Elasticsearch:
65
+ global _tunnel, _es_client
66
+ if _es_client is not None:
67
+ return _es_client
68
+
69
+ ssh_host = os.getenv("SSH_HOST", "").strip().strip('"')
70
+ if ssh_host:
71
+ _tunnel, local_port = _start_tunnel()
72
+ _es_client = _build_es_client("127.0.0.1", local_port)
73
+ else:
74
+ _es_client = _build_es_client(
75
+ os.getenv("ES_HOST", "localhost"),
76
+ int(os.getenv("ES_PORT", "9200")),
77
+ )
78
+
79
+ return _es_client
80
+
81
+
82
+ def shutdown():
83
+ global _tunnel, _es_client
84
+ if _es_client:
85
+ _es_client.close()
86
+ _es_client = None
87
+ if _tunnel:
88
+ _tunnel.stop()
89
+ _tunnel = None
90
+
91
+
92
+ # ---------------------------------------------------------------------------
93
+ # MCP server
94
+ # ---------------------------------------------------------------------------
95
+
96
+ mcp = FastMCP("elasticsearch-logs")
97
+
98
+
99
+ @mcp.tool()
100
+ def list_indices(pattern: str = "*") -> str:
101
+ """List Elasticsearch indices matching a glob pattern (default: all)."""
102
+ es = get_es()
103
+ resp = es.cat.indices(index=pattern, h="index,health,status,docs.count,store.size", s="index", format="json")
104
+ return json.dumps(resp.body, indent=2)
105
+
106
+
107
+ @mcp.tool()
108
+ def search_logs(
109
+ index: str,
110
+ query: str = "",
111
+ size: int = 20,
112
+ from_: int = 0,
113
+ sort_field: str = "@timestamp",
114
+ sort_order: str = "desc",
115
+ filters: str = "",
116
+ ) -> str:
117
+ """
118
+ Search logs in an Elasticsearch index.
119
+
120
+ Args:
121
+ index: Index name or pattern (e.g. "logs-*").
122
+ query: Lucene/simple query string. Empty returns all docs.
123
+ size: Number of hits to return (max 1000).
124
+ from_: Pagination offset.
125
+ sort_field: Field to sort by (default: @timestamp).
126
+ sort_order: "asc" or "desc".
127
+ filters: JSON string of extra must-term filters, e.g.
128
+ '[{"term": {"level": "ERROR"}}]'.
129
+ """
130
+ es = get_es()
131
+ size = min(size, 1000)
132
+
133
+ must: list[Any] = []
134
+ if query:
135
+ must.append({"query_string": {"query": query}})
136
+ if filters:
137
+ extra = json.loads(filters)
138
+ must.extend(extra)
139
+
140
+ body: dict[str, Any] = {
141
+ "query": {"bool": {"must": must}} if must else {"match_all": {}},
142
+ "sort": [{sort_field: {"order": sort_order}}],
143
+ "size": size,
144
+ "from": from_,
145
+ }
146
+
147
+ resp = es.search(index=index, body=body)
148
+ hits = resp["hits"]["hits"]
149
+ total = resp["hits"]["total"]["value"]
150
+ return json.dumps({"total": total, "hits": [h["_source"] for h in hits]}, indent=2, default=str)
151
+
152
+
153
+ @mcp.tool()
154
+ def get_recent_errors(
155
+ index: str,
156
+ size: int = 20,
157
+ level_field: str = "level",
158
+ level_value: str = "ERROR",
159
+ minutes: int = 60,
160
+ ) -> str:
161
+ """
162
+ Fetch recent error-level log entries from the last N minutes.
163
+
164
+ Args:
165
+ index: Index name or pattern.
166
+ size: Number of results.
167
+ level_field: Field name that holds the log level.
168
+ level_value: The error level value to filter on (e.g. ERROR, CRITICAL).
169
+ minutes: Look back window in minutes.
170
+ """
171
+ es = get_es()
172
+ body: dict[str, Any] = {
173
+ "query": {
174
+ "bool": {
175
+ "must": [
176
+ {"term": {level_field: level_value}},
177
+ {"range": {"@timestamp": {"gte": f"now-{minutes}m", "lte": "now"}}},
178
+ ]
179
+ }
180
+ },
181
+ "sort": [{"@timestamp": {"order": "desc"}}],
182
+ "size": min(size, 1000),
183
+ }
184
+ resp = es.search(index=index, body=body)
185
+ hits = resp["hits"]["hits"]
186
+ total = resp["hits"]["total"]["value"]
187
+ return json.dumps({"total": total, "hits": [h["_source"] for h in hits]}, indent=2, default=str)
188
+
189
+
190
+ @mcp.tool()
191
+ def get_index_mapping(index: str) -> str:
192
+ """Return the field mapping for an Elasticsearch index."""
193
+ es = get_es()
194
+ resp = es.indices.get_mapping(index=index)
195
+ return json.dumps(resp.body, indent=2)
196
+
197
+
198
+ @mcp.tool()
199
+ def run_aggregation(
200
+ index: str,
201
+ aggs: str,
202
+ query: str = "",
203
+ ) -> str:
204
+ """
205
+ Run a custom aggregation against an index.
206
+
207
+ Args:
208
+ index: Index name or pattern.
209
+ aggs: JSON string of an Elasticsearch aggregations object, e.g.
210
+ '{"by_level": {"terms": {"field": "level", "size": 10}}}'.
211
+ query: Optional Lucene query string to filter docs before aggregating.
212
+ """
213
+ es = get_es()
214
+ body: dict[str, Any] = {"size": 0, "aggs": json.loads(aggs)}
215
+ if query:
216
+ body["query"] = {"query_string": {"query": query}}
217
+ resp = es.search(index=index, body=body)
218
+ return json.dumps(resp["aggregations"], indent=2, default=str)
219
+
220
+
221
+ @mcp.tool()
222
+ def connection_info() -> str:
223
+ """Show current connection details (host, SSH tunnel status)."""
224
+ ssh_host = os.getenv("SSH_HOST", "").strip()
225
+ info: dict[str, Any] = {
226
+ "mode": "ssh_tunnel" if ssh_host else "direct",
227
+ "es_host": os.getenv("ES_HOST", "localhost"),
228
+ "es_port": os.getenv("ES_PORT", "9200"),
229
+ }
230
+ if ssh_host:
231
+ info["ssh_host"] = ssh_host
232
+ info["ssh_user"] = os.getenv("SSH_USERNAME", "ubuntu")
233
+ info["ssh_pem"] = os.getenv("SSH_PEM_FILE", "~/.ssh/id_rsa")
234
+ info["remote_es"] = (
235
+ f"{os.getenv('SSH_REMOTE_ES_HOST', 'localhost')}:"
236
+ f"{os.getenv('SSH_REMOTE_ES_PORT', '9200')}"
237
+ )
238
+ if _tunnel and _tunnel.is_active:
239
+ info["tunnel_local_port"] = _tunnel.local_bind_port
240
+ info["tunnel_active"] = True
241
+ return json.dumps(info, indent=2)
242
+
243
+
244
+ # ---------------------------------------------------------------------------
245
+ # Entry point
246
+ # ---------------------------------------------------------------------------
247
+
248
+ def main():
249
+ import atexit
250
+ atexit.register(shutdown)
251
+ mcp.run(transport="stdio")
252
+
253
+
254
+ if __name__ == "__main__":
255
+ main()