openwebui-mcp 0.1.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,15 @@
1
+ """Open WebUI MCP server - ask models with tool support over MCP.
2
+
3
+ Public surface:
4
+
5
+ * ``config.Settings`` - server/connection configuration (env driven)
6
+ * ``server.create_server`` - build a ``FastMCP`` instance exposing the tools
7
+ * ``__main__.main`` - CLI entry point (``openwebui-mcp``)
8
+ """
9
+
10
+ from openwebui_mcp.config import Settings
11
+ from openwebui_mcp.server import create_server
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ __all__ = ["Settings", "__version__", "create_server"]
@@ -0,0 +1,70 @@
1
+ """CLI entry point for the Open WebUI MCP server.
2
+
3
+ Run ``openwebui-mcp`` (stdio by default) or ``python -m openwebui_mcp``.
4
+ Configure via env vars or a ``.env`` file in the working directory.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import logging
11
+ import sys
12
+
13
+ from openwebui_mcp.config import Settings, load_dotenv
14
+ from openwebui_mcp.server import create_server
15
+
16
+ VALID_TRANSPORTS = ("stdio", "sse", "streamable-http")
17
+
18
+
19
+ def build_parser() -> argparse.ArgumentParser:
20
+ parser = argparse.ArgumentParser(
21
+ prog="openwebui-mcp",
22
+ description="Open WebUI MCP server: ask models with tool support over MCP",
23
+ )
24
+ parser.add_argument(
25
+ "--transport",
26
+ choices=VALID_TRANSPORTS,
27
+ help="MCP transport (default: stdio). Overrides OPENWEBUI_MCP_TRANSPORT.",
28
+ )
29
+ parser.add_argument(
30
+ "--name",
31
+ help="Server name shown to clients (default: %(default)r)",
32
+ default="openwebui",
33
+ )
34
+ parser.add_argument("--host", help="HTTP bind host for sse/streamable-http")
35
+ parser.add_argument(
36
+ "--port", type=int, help="HTTP bind port for sse/streamable-http"
37
+ )
38
+ parser.add_argument(
39
+ "--log-level",
40
+ choices=("DEBUG", "INFO", "WARNING", "ERROR"),
41
+ default="INFO",
42
+ help="Logging verbosity (default: INFO)",
43
+ )
44
+ return parser
45
+
46
+
47
+ def main(argv: list[str] | None = None) -> int:
48
+ load_dotenv()
49
+ args = build_parser().parse_args(argv)
50
+
51
+ logging.basicConfig(level=getattr(logging, args.log_level))
52
+
53
+ overrides: dict[str, str] = {}
54
+ if args.transport:
55
+ overrides["transport"] = args.transport
56
+ if args.name:
57
+ overrides["name"] = args.name
58
+ if args.host:
59
+ overrides["host"] = args.host
60
+ if args.port is not None:
61
+ overrides["port"] = str(args.port)
62
+
63
+ settings = Settings.from_env(**overrides)
64
+ server = create_server(settings)
65
+ server.run(transport=settings.transport)
66
+ return 0
67
+
68
+
69
+ if __name__ == "__main__":
70
+ sys.exit(main())
@@ -0,0 +1,158 @@
1
+ """Connection and server settings for the Open WebUI MCP server.
2
+
3
+ Everything is read from environment variables (and an optional ``.env`` file),
4
+ the standard way MCP clients inject config. Precedence: first defined env var
5
+ wins, so the common aliases act as fallbacks for each other.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import os
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Literal, cast
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ # Accepted env var names, in precedence order, for each setting.
19
+ _BASE_URL_VARS = ("OPENWEBUI_BASE_URL", "OPENWEBUI_URL", "OWUI_URL")
20
+ _TOKEN_VARS = ("OPENWEBUI_API_KEY", "OPENWEBUI_TOKEN", "OWUI_API_KEY", "OWUI_TOKEN")
21
+ _DEFAULT_MODEL_VARS = ("OPENWEBUI_DEFAULT_MODEL", "OWUI_DEFAULT_MODEL")
22
+ _ENFORCE_DEFAULT_MODEL_VARS = (
23
+ "OPENWEBUI_ENFORCE_DEFAULT_MODEL",
24
+ "OWUI_ENFORCE_DEFAULT_MODEL",
25
+ )
26
+ _MCP_TOKEN_VARS = ("OPENWEBUI_MCP_TOKEN", "OWUI_MCP_TOKEN")
27
+ _TRANSPORT_VARS = ("OPENWEBUI_MCP_TRANSPORT", "OWUI_MCP_TRANSPORT")
28
+ _SSL_CA_VARS = ("OPENWEBUI_CA_BUNDLE", "OWUI_CA_BUNDLE")
29
+ _SSL_VERIFY_VARS = ("OPENWEBUI_SSL_VERIFY", "OWUI_SSL_VERIFY")
30
+ _ASK_DESCRIPTION_VARS = ("OPENWEBUI_ASK_DESCRIPTION", "OWUI_ASK_DESCRIPTION")
31
+ _INSTRUCTIONS_VARS = ("OPENWEBUI_INSTRUCTIONS", "OWUI_INSTRUCTIONS")
32
+
33
+ # MCP transports FastMCP can run on; validated at config time.
34
+ Transport = Literal["stdio", "sse", "streamable-http"]
35
+ _VALID_TRANSPORTS: tuple[str, ...] = ("stdio", "sse", "streamable-http")
36
+
37
+
38
+ def _first(*names: str, default: str | None = None) -> str | None:
39
+ """Return the first env var from ``names`` that is set (non-empty)."""
40
+ for name in names:
41
+ value = os.getenv(name, "").strip()
42
+ if value:
43
+ return value
44
+ return default
45
+
46
+
47
+ def load_dotenv(path: str | Path | None = None) -> None:
48
+ """Load a ``.env`` file next to the current working directory.
49
+
50
+ Uses python-dotenv if installed (it ships with the ``mcp`` dependency);
51
+ does nothing when the file is absent. Harmless no-op otherwise.
52
+ """
53
+ try:
54
+ from dotenv import load_dotenv as _load
55
+ except ImportError: # pragma: no cover - dotenv is a transitive dep
56
+ logger.debug("python-dotenv not available; skipping .env load")
57
+ return
58
+ target = Path(path) if path else Path.cwd() / ".env"
59
+ if target.exists():
60
+ _load(target)
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class Settings:
65
+ """Resolved server configuration.
66
+
67
+ ``base_url`` and ``token`` are required: they are the Open WebUI server the
68
+ SDK talks to and the bearer token (API key) used for authentication.
69
+ ``mcp_token`` is optional and, when set, turns on bearer-token auth for the
70
+ MCP endpoint itself (see ``server.create_server``).
71
+ """
72
+
73
+ base_url: str
74
+ token: str
75
+ name: str = "openwebui"
76
+ # Model used by ``ask`` when the caller does not pass one explicitly.
77
+ default_model: str | None = None
78
+ # When true, ``ask`` always uses ``default_model`` and ignores the caller's
79
+ # ``model`` argument (must be paired with ``default_model``).
80
+ enforce_default_model: bool = False
81
+ mcp_token: str | None = None
82
+ timeout_ms: int = 120_000
83
+ transport: Transport = "stdio"
84
+ host: str = "127.0.0.1"
85
+ port: int = 8000
86
+ # TLS options for talking to Open WebUI over https. ``ssl_ca_bundle`` is a
87
+ # PEM CA file to trust (private/Traefik CA, or this env's mitm CA);
88
+ # ``ssl_verify`` disables certificate verification for the JSON routes.
89
+ ssl_ca_bundle: str | None = None
90
+ ssl_verify: bool = True
91
+ # Custom description for the ``ask`` tool; when set it replaces the built-in
92
+ # docstring description. Lets operators inject agent-facing instructions.
93
+ ask_description: str | None = None
94
+ # Server-wide ``instructions`` surfaced in the MCP initialize response.
95
+ # Codex and other hosts read it as usage guidance for the whole server, so
96
+ # this is where to tell agents to use the tools proactively.
97
+ instructions: str | None = None
98
+
99
+ @classmethod
100
+ def from_env(cls, **overrides: str) -> Settings:
101
+ """Build settings from env vars; ``overrides`` win for tests/callers."""
102
+ base_url = _first(*_BASE_URL_VARS) or overrides.get("base_url")
103
+ token = _first(*_TOKEN_VARS) or overrides.get("token")
104
+ if not base_url or not token:
105
+ raise ValueError(
106
+ "Open WebUI connection not configured: set OPENWEBUI_BASE_URL "
107
+ "and OPENWEBUI_API_KEY (or the aliases OPENWEBUI_URL / "
108
+ "OPENWEBUI_TOKEN)"
109
+ )
110
+ mcp_token = overrides.get("mcp_token") or _first(*_MCP_TOKEN_VARS)
111
+ default_model = overrides.get("default_model") or _first(*_DEFAULT_MODEL_VARS)
112
+ transport = overrides.get("transport") or _first(*_TRANSPORT_VARS) or "stdio"
113
+ if transport not in _VALID_TRANSPORTS:
114
+ raise ValueError(
115
+ f"invalid transport {transport!r}; pick one of "
116
+ + ", ".join(_VALID_TRANSPORTS)
117
+ )
118
+ # Membership in _VALID_TRANSPORTS (exactly the three Literal values)
119
+ # makes this cast sound; it just narrows ``str`` back to ``Transport``.
120
+ transport = cast(Transport, transport)
121
+ try:
122
+ timeout_ms = int(
123
+ overrides.get("timeout_ms") or os.getenv("OWUI_TIMEOUT_MS", "120000")
124
+ )
125
+ except ValueError as exc:
126
+ raise ValueError(f"invalid OWUI_TIMEOUT_MS: {exc}") from exc
127
+ try:
128
+ port = int(overrides.get("port", "8000"))
129
+ except ValueError as exc:
130
+ raise ValueError(f"invalid port: {exc}") from exc
131
+ verify_raw = (
132
+ overrides.get("ssl_verify")
133
+ or _first(*_SSL_VERIFY_VARS, default="true")
134
+ or "true"
135
+ )
136
+ enforce_raw = (
137
+ overrides.get("enforce_default_model")
138
+ or _first(*_ENFORCE_DEFAULT_MODEL_VARS, default="false")
139
+ or "false"
140
+ )
141
+ return cls(
142
+ base_url=base_url,
143
+ token=token,
144
+ name=overrides.get("name", "openwebui"),
145
+ mcp_token=mcp_token,
146
+ default_model=default_model,
147
+ enforce_default_model=enforce_raw.strip().lower()
148
+ not in ("0", "false", "no", "off"),
149
+ transport=transport,
150
+ timeout_ms=timeout_ms,
151
+ host=overrides.get("host", "127.0.0.1"),
152
+ port=port,
153
+ ssl_ca_bundle=overrides.get("ssl_ca_bundle") or _first(*_SSL_CA_VARS),
154
+ ssl_verify=verify_raw.strip().lower() not in ("0", "false", "no", "off"),
155
+ ask_description=overrides.get("ask_description")
156
+ or _first(*_ASK_DESCRIPTION_VARS),
157
+ instructions=overrides.get("instructions") or _first(*_INSTRUCTIONS_VARS),
158
+ )
openwebui_mcp/py.typed ADDED
File without changes
@@ -0,0 +1,308 @@
1
+ """FastMCP server exposing Open WebUI as MCP tools.
2
+
3
+ Two tools, per spec:
4
+
5
+ * ``ask`` - send a prompt to a model. The model is a required argument. Runs
6
+ the Open WebUI tool-calling loop: any tools attached to the model are
7
+ enabled automatically (``OpenWebUIClient.resolve_tools``) and results come
8
+ back as a structured dict (answer, reasoning, tool_calls).
9
+ * ``list_models`` - list the models the connected Open WebUI user can see.
10
+
11
+ Authentication: the server itself talks to Open WebUI with a bearer token (as
12
+ ``Authorization: Bearer``) carried by the SDK client. When a static MCP token
13
+ is configured (``OPENWEBUI_MCP_TOKEN``) the MCP endpoint additionally requires
14
+ ``Authorization: Bearer <token>`` on every request.
15
+
16
+ Note on the event loop: the SDK ships a sync ``run_chat`` that wraps its async
17
+ Socket.IO runner in ``asyncio.run``. That works for the CLI (main thread, no
18
+ loop running) but NOT inside an async server: ``asyncio.run`` from a running
19
+ loop raises, and nesting it in ``asyncio.to_thread`` starves the socket
20
+ background tasks so completion events never arrive (the tool hangs). So the
21
+ ``ask`` handler awaits the SDK's async ``sockets.run_chat_with_tools`` directly
22
+ on this event loop - one loop owns the aiohttp session, the socketio client and
23
+ the completion event, exactly like the CLI's single loop. Blocking SDK work
24
+ without tools (plain HTTP) is still offloaded via ``asyncio.to_thread``.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import asyncio
30
+ import inspect
31
+ import logging
32
+ import os
33
+ import ssl
34
+ from typing import Any
35
+
36
+ from mcp.server.auth.provider import AccessToken, TokenVerifier
37
+ from mcp.server.auth.settings import AuthSettings
38
+ from mcp.server.fastmcp import FastMCP
39
+ from openwebui_sdk import OpenWebUIClient
40
+ from pydantic import AnyHttpUrl
41
+
42
+ from openwebui_mcp.config import Settings
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+ # SDK models attach tools under info.meta.toolIds; we surface that in
47
+ # list_models so callers can see which tools a model can invoke.
48
+ _TOOL_FIELDS = "tool_ids"
49
+
50
+
51
+ class StaticTokenVerifier(TokenVerifier):
52
+ """Accepts exactly one configured bearer token (constant-time compare)."""
53
+
54
+ def __init__(self, token: str) -> None:
55
+ self._token = token
56
+
57
+ async def verify_token(self, token: str) -> AccessToken | None:
58
+ if len(token) != len(self._token):
59
+ return None
60
+ if sum(a != b for a, b in zip(token, self._token, strict=True)) != 0:
61
+ return None
62
+ return AccessToken(
63
+ token=token,
64
+ client_id="openwebui-mcp",
65
+ scopes=["all"],
66
+ subject=token,
67
+ )
68
+
69
+
70
+ def _mcp_endpoint_url(settings: Settings) -> AnyHttpUrl:
71
+ """Dummy discovery URL used by AuthSettings when MCP token auth is on.
72
+
73
+ Bearer verification via ``StaticTokenVerifier`` never consults OAuth
74
+ discovery, so the URL only needs to be syntactically valid.
75
+ """
76
+ return AnyHttpUrl(f"http://{settings.host}:{settings.port}/mcp")
77
+
78
+
79
+ def ask_description(fn: Any, settings: Settings) -> str:
80
+ """Description shown for the ``ask`` tool to MCP agents.
81
+
82
+ The full docstring is always kept; ``settings.ask_description`` (from
83
+ ``OPENWEBUI_ASK_DESCRIPTION``) only replaces the first summary line so
84
+ operators can reword it without losing the stateless/history guidance.
85
+ """
86
+ doc = inspect.getdoc(fn) or ""
87
+ summary, sep, rest = doc.partition("\n")
88
+ summary = settings.ask_description or summary
89
+ return f"{summary}{sep}{rest}".strip()
90
+
91
+
92
+ def apply_tls_settings(settings: Settings) -> None:
93
+ """Apply TLS trust config to this process before any SDK request.
94
+
95
+ ``OPENWEBUI_CA_BUNDLE`` - set ``SSL_CERT_FILE`` so every
96
+ ``create_default_context`` caller (urllib for the JSON routes, aiohttp for
97
+ the Socket.IO tool loop) trusts the given PEM CA. ``OPENWEBUI_SSL_VERIFY``
98
+ false - drop certificate verification for the JSON (urllib) routes against
99
+ self-signed / private-CA servers. No-op (and safe to call always) when
100
+ neither is configured.
101
+ """
102
+ if settings.ssl_ca_bundle:
103
+ os.environ["SSL_CERT_FILE"] = settings.ssl_ca_bundle
104
+ if not settings.ssl_verify and hasattr(ssl, "_create_default_https_context"):
105
+ ssl._create_default_https_context = ssl._create_unverified_context
106
+
107
+
108
+ def create_server(
109
+ settings: Settings, *, client: OpenWebUIClient | None = None
110
+ ) -> FastMCP:
111
+ """Build a configured FastMCP instance exposing the Open WebUI tools.
112
+
113
+ ``client`` is injectable for tests; when omitted a client is created from
114
+ ``settings`` (base URL + bearer token). When ``settings.mcp_token`` is set
115
+ the MCP endpoint requires ``Authorization: Bearer <token>`` on requests.
116
+ """
117
+ apply_tls_settings(settings)
118
+ owui = client or OpenWebUIClient(base_url=settings.base_url, token=settings.token)
119
+
120
+ mcp = FastMCP(
121
+ settings.name,
122
+ instructions=settings.instructions,
123
+ host=settings.host,
124
+ port=settings.port,
125
+ auth=(
126
+ AuthSettings(
127
+ issuer_url=_mcp_endpoint_url(settings),
128
+ resource_server_url=_mcp_endpoint_url(settings),
129
+ )
130
+ if settings.mcp_token
131
+ else None
132
+ ),
133
+ token_verifier=(
134
+ StaticTokenVerifier(settings.mcp_token) if settings.mcp_token else None
135
+ ),
136
+ )
137
+
138
+ def _list_models_sync() -> list[dict[str, Any]]:
139
+ models = owui.list_models()
140
+ return [
141
+ {
142
+ "id": m.id,
143
+ "name": m.name,
144
+ _TOOL_FIELDS: m.tool_ids or [],
145
+ }
146
+ for m in models
147
+ ]
148
+
149
+ @mcp.tool()
150
+ async def list_models() -> list[dict[str, Any]]:
151
+ """List the models available on the connected Open WebUI server.
152
+
153
+ Returns one entry per model with its id, display name, and the ids of
154
+ any tools attached to it. Use the returned ids as the ``model``
155
+ argument of the ``ask`` tool.
156
+ """
157
+ return await asyncio.to_thread(_list_models_sync)
158
+
159
+ def _ask_no_tools_sync(
160
+ model: str,
161
+ messages: list[dict[str, str]],
162
+ temperature: float | None,
163
+ timeout_s: int,
164
+ ) -> dict[str, Any]:
165
+ """Plain HTTP streaming path (no Socket.IO). Blocking; run in a thread."""
166
+ result = owui.run_chat(
167
+ model=model,
168
+ messages=messages,
169
+ tool_ids=[],
170
+ temperature=temperature,
171
+ timeout=timeout_s,
172
+ )
173
+ return {
174
+ "answer": result.answer,
175
+ "reasoning": result.reasoning,
176
+ "tool_calls": result.tool_calls,
177
+ }
178
+
179
+ async def ask(
180
+ prompt: str,
181
+ model: str | None = None,
182
+ system: str | None = None,
183
+ temperature: float | None = None,
184
+ use_tools: bool = True,
185
+ history: list[dict[str, str]] | None = None,
186
+ ) -> dict[str, Any]:
187
+ """Ask an Open WebUI model a question, with tool support.
188
+
189
+ IMPORTANT - this MCP server is stateless: every call starts a FRESH
190
+ conversation on the remote model. The remote model does NOT remember
191
+ previous calls. To carry context between questions, pass the relevant
192
+ prior exchanges in ``history`` as ``[{"role": "user"|"assistant",
193
+ "content": ...}]`` (your earlier question and its answer, in order),
194
+ or include the needed context directly in ``prompt``.
195
+
196
+ When ``model`` is omitted the configured default
197
+ (``OPENWEBUI_DEFAULT_MODEL``) is used; if that is also unset the call
198
+ fails. When ``OPENWEBUI_ENFORCE_DEFAULT_MODEL`` is on the configured
199
+ default is always used and the caller's ``model`` is ignored. Tools
200
+ attached to the model are enabled by default (``use_tools``) and run
201
+ server-side through Open WebUI's Socket.IO tool loop, so answers may
202
+ be produced with real tool calls.
203
+
204
+ Args:
205
+ prompt: The user message to send to the model.
206
+ model: Open WebUI model id to ask, e.g. "sample-workspace-model-1",
207
+ or from ``list_models``. Defaults to OPENWEBUI_DEFAULT_MODEL.
208
+ system: Optional system prompt leading the conversation.
209
+ temperature: Optional sampling temperature override.
210
+ use_tools: Enable tools attached to the model (default True).
211
+ history: Optional prior turns ``[{"role": "user"|"assistant",
212
+ "content": ...}]`` sent before ``prompt`` (and after any
213
+ ``system`` prompt) so the remote model keeps context from
214
+ earlier questions.
215
+
216
+ Returns:
217
+ Dict with the answer text, optional reasoning, and any tool calls
218
+ made: {"answer", "reasoning", "tool_calls"}. The "answer" may contain
219
+ links, treat these as information sources, and cite as needed.
220
+ """
221
+ import time
222
+
223
+ from openwebui_sdk import sockets
224
+
225
+ if settings.enforce_default_model:
226
+ # Enforce mode: the server-side default always wins over caller input.
227
+ model = settings.default_model
228
+ else:
229
+ model = model or settings.default_model
230
+ if not model:
231
+ raise ValueError(
232
+ "no model specified: pass a model to ask or set OPENWEBUI_DEFAULT_MODEL"
233
+ )
234
+
235
+ # SDK timeouts are in SECONDS (http.DEFAULT_TIMEOUT=60); settings in ms.
236
+ timeout_s = max(1, settings.timeout_ms // 1000)
237
+ messages: list[dict[str, str]] = []
238
+ if system:
239
+ messages.append({"role": "system", "content": system})
240
+ if history:
241
+ messages.extend(history)
242
+ messages.append({"role": "user", "content": prompt})
243
+
244
+ tool_ids = (
245
+ await asyncio.to_thread(owui.resolve_tools, model) if use_tools else []
246
+ )
247
+ logger.info(
248
+ "ask: model=%s tools=%s timeout=%ss", model, tool_ids or "(none)", timeout_s
249
+ )
250
+
251
+ started = time.monotonic()
252
+ try:
253
+ if tool_ids:
254
+ # Await the SDK's async Socket.IO runner DIRECTLY on this event
255
+ # loop - exactly how the CLI awaits it on its loop. Nesting the
256
+ # SDK's asyncio.run inside asyncio.to_thread broke event
257
+ # delivery (socket background tasks never pumped); running on
258
+ # this loop keeps the aiohttp session + socketio client + the
259
+ # completion event on one loop, so chat-events flow back.
260
+ data = await asyncio.wait_for(
261
+ sockets.run_chat_with_tools(
262
+ base_url=settings.base_url,
263
+ token=settings.token,
264
+ model=model,
265
+ messages=messages,
266
+ tool_ids=tool_ids,
267
+ timeout=timeout_s,
268
+ on_status=lambda s: logger.info(
269
+ "ask[%s]: status: %s", model, s
270
+ ),
271
+ on_tool=lambda s: logger.info("ask[%s]: tool: %s", model, s),
272
+ on_reasoning=lambda s: logger.debug(
273
+ "ask[%s]: reasoning: %s", model, (s or "")[:200]
274
+ ),
275
+ ),
276
+ timeout=timeout_s + 60,
277
+ )
278
+ result = {
279
+ "answer": data.get("answer", ""),
280
+ "reasoning": data.get("reasoning"),
281
+ "tool_calls": data.get("tool_calls", []),
282
+ }
283
+ else:
284
+ # No tools: plain HTTP streaming path (blocking) - offload.
285
+ result = await asyncio.to_thread(
286
+ _ask_no_tools_sync,
287
+ model,
288
+ messages,
289
+ temperature,
290
+ timeout_s,
291
+ )
292
+ except TimeoutError:
293
+ logger.error("ask: timed out after %ss for model=%s", timeout_s + 60, model)
294
+ raise RuntimeError(
295
+ f"Open WebUI did not complete within {timeout_s + 60}s"
296
+ ) from None
297
+ logger.info(
298
+ "ask: done in %.1fs (tools=%d)",
299
+ time.monotonic() - started,
300
+ len(result.get("tool_calls") or []),
301
+ )
302
+ return result
303
+
304
+ # Register ``ask`` with a composed description: the full docstring is
305
+ # always shown, with only the first summary line replaceable via env.
306
+ mcp.tool(description=ask_description(ask, settings), name="ask")(ask)
307
+
308
+ return mcp
@@ -0,0 +1,285 @@
1
+ Metadata-Version: 2.4
2
+ Name: openwebui-mcp
3
+ Version: 0.1.1
4
+ Summary: Open WebUI MCP server (FastMCP) - ask models with tool support, list models
5
+ Author: Alexey @vedmaka
6
+ License: MIT
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: mcp<2,>=1.20
10
+ Requires-Dist: openwebui-sdk>=0.1.1
11
+ Requires-Dist: python-dotenv>=1.0
12
+
13
+ # openwebui-mcp
14
+
15
+ Open WebUI MCP server built on [FastMCP](https://github.com/modelcontextprotocol/python-sdk)
16
+ and the [openwebui-sdk](https://github.com/vedmaka/openwebui-sdk) library
17
+
18
+ Lets any MCP client (Claude Desktop, Cursor, agents) ask Open WebUI models
19
+ through the full tool-calling loop, not just plain chat
20
+
21
+ <img width="3680" height="2592" alt="ray-so-export (1)" src="https://github.com/user-attachments/assets/01e7ed7f-35a5-413e-9b26-27ac823d7c74" />
22
+
23
+ ## Quick start
24
+
25
+ ```bash
26
+ OPENWEBUI_BASE_URL=http://localhost:8080 OPENWEBUI_API_KEY=sk-... \
27
+ uvx openwebui-mcp # stdio (default) - installs and runs from PyPI
28
+ ```
29
+
30
+ ### Connect an MCP client
31
+
32
+ **Codex CLI** (`~/.codex/config.toml`) - register the server as `owui` and let
33
+ it call tools without approval:
34
+
35
+ ```toml
36
+ [mcp_servers.owui]
37
+ command = "uvx"
38
+ args = ["openwebui-mcp"]
39
+ env = {
40
+ OPENWEBUI_BASE_URL = "http://localhost:8080",
41
+ OPENWEBUI_API_KEY = "sk-..."
42
+ }
43
+ default_tools_approval_mode = "auto"
44
+ ```
45
+
46
+ **Claude Desktop** (`claude_desktop_config.json`):
47
+
48
+ ```json
49
+ {
50
+ "mcpServers": {
51
+ "openwebui": {
52
+ "command": "uvx",
53
+ "args": ["openwebui-mcp"],
54
+ "env": {
55
+ "OPENWEBUI_BASE_URL": "http://localhost:8080",
56
+ "OPENWEBUI_API_KEY": "sk-..."
57
+ }
58
+ }
59
+ }
60
+ }
61
+ ```
62
+
63
+ The quick start uses stdio, so each client spawns the server locally. For
64
+ remote HTTP transports, open the collapsible options below (or see Run)
65
+
66
+ <details>
67
+ <summary>SSE setup (Claude Desktop and other SSE-capable clients)</summary>
68
+
69
+ Run the server:
70
+
71
+ ```bash
72
+ uvx openwebui-mcp --transport sse --host 0.0.0.0 --port 8000
73
+ ```
74
+
75
+ **Claude Desktop** (`claude_desktop_config.json`) - SSE endpoint is `http://<host>:8000/sse`:
76
+
77
+ ```json
78
+ {
79
+ "mcpServers": {
80
+ "openwebui": {
81
+ "type": "sse",
82
+ "url": "http://<host>:8000/sse"
83
+ }
84
+ }
85
+ }
86
+ ```
87
+
88
+ </details>
89
+
90
+ <details>
91
+ <summary>Streamable HTTP setup (Codex CLI, rmcp, agents over HTTP)</summary>
92
+
93
+ Run the server:
94
+
95
+ ```bash
96
+ uvx openwebui-mcp --transport streamable-http --host 0.0.0.0 --port 8000
97
+ ```
98
+
99
+ **Codex CLI** (`~/.codex/config.toml`) - streamable-http endpoint is `http://<host>:8000/mcp`:
100
+
101
+ ```toml
102
+ [mcp_servers.owui]
103
+ url = "http://<host>:8000/mcp"
104
+ default_tools_approval_mode = "auto"
105
+ ```
106
+
107
+ A bare `http://<host>:8000` returns 404 on initialize; point the client URL at
108
+ the full `/mcp` path. rmcp and other streamable-http clients use the same URL
109
+
110
+ </details>
111
+
112
+ ## Proactive ask skill
113
+
114
+ The repo ships a skill that makes an agent consult the `ask` tool eagerly
115
+ instead of only when it happens to choose to:
116
+
117
+ ```text
118
+ skills/owui-proactive-ask/SKILL.md
119
+ ```
120
+
121
+ It instructs the agent to call `mcp__owui__ask` before answering **every**
122
+ explicit or implicit question (advice, explanations, recommendations,
123
+ troubleshooting, follow-ups), pass relevant conversation context via
124
+ `history`, keep remote tools enabled (`use_tools: true`), and validate the OWUI
125
+ answer against local evidence before replying. It also covers failure handling
126
+ (retry, fall back, say it failed - never fake an OWUI result).
127
+
128
+ Install it with the agent skills CLI (`npx skills`) or manually:
129
+
130
+ ```bash
131
+ # global install for Codex
132
+ npx skills add ./skills/owui-proactive-ask -g -a codex -y
133
+
134
+ # global install for Claude Code
135
+ npx skills add ./skills/owui-proactive-ask -g -a claude-code -y
136
+
137
+ # or copy the folder into your agent's skills directory
138
+ cp -r skills/owui-proactive-ask ~/.agents/skills/
139
+ ```
140
+
141
+ The skill references the tool as `mcp__owui__ask`, so register the MCP server
142
+ under the name `owui` (Codex-style clients name MCP tools
143
+ `mcp__<server>__<tool>`, see `[mcp_servers.owui]` in Quick start above).
144
+
145
+ The skill pairs with `OPENWEBUI_ASK_DESCRIPTION` and `OPENWEBUI_INSTRUCTIONS`
146
+ (see Configure): the skill makes the agent call `ask`, while the description
147
+ and instructions tell the model why and when.
148
+
149
+ ## Tools
150
+
151
+ Exactly two tools are exposed
152
+
153
+ ### `ask`
154
+
155
+ Send a prompt to a model with Open WebUI tool support
156
+
157
+ - `prompt` (required) - the user message
158
+ - `model` (optional) - the model id to ask, e.g. one returned by `list_models`.
159
+ Omitted, the server uses the configured `OPENWEBUI_DEFAULT_MODEL`; if that
160
+ is also unset the call fails with an error
161
+ - `system` (optional) - a system prompt leading the conversation
162
+ - `temperature` (optional) - sampling temperature override
163
+ - `use_tools` (optional, default true) - enable the tools attached to the model
164
+ - `history` (optional) - prior turns `[{"role": "user"|"assistant", "content": "..."}]`
165
+ sent before `prompt` so the remote model keeps context from earlier questions
166
+
167
+ **Stateless**: each `ask` call is a fresh conversation on the remote model - it
168
+ never remembers previous calls. To carry context across questions, pass the
169
+ relevant earlier exchanges in `history` (e.g. your prior question and its
170
+ answer), or inline the context into `prompt`. Agents that keep their own
171
+ conversation log should replay the needed turns via `history`
172
+
173
+ To lock every call to one model regardless of what the client passes, set
174
+ `OPENWEBUI_ENFORCE_DEFAULT_MODEL=true` (requires `OPENWEBUI_DEFAULT_MODEL`);
175
+ `ask` then ignores the `model` argument entirely
176
+
177
+ To control what agents see about this tool, set `OPENWEBUI_ASK_DESCRIPTION` -
178
+ it replaces only the first summary line of the tool description (the text
179
+ agents read to decide how to call `ask`). The `IMPORTANT - this MCP server is
180
+ stateless` block, the argument docs and the default-model guidance are always
181
+ present. Unset, the built-in summary line is used
182
+
183
+ Tools attached to the model run server-side through Open WebUI's Socket.IO
184
+ tool loop, so answers can be produced with real tool calls. Result is a struct
185
+ with `answer`, `reasoning` and `tool_calls`
186
+
187
+ ### `list_models`
188
+
189
+ List the models the connected Open WebUI user can see. Each entry carries the
190
+ model `id`, display `name` and the `tool_ids` attached to it
191
+
192
+ ## Authentication
193
+
194
+ Token-based, in two layers
195
+
196
+ 1. **Open WebUI access** (required). The server talks to Open WebUI as
197
+ `Authorization: Bearer <token>`. Provide an API key or JWT via env:
198
+
199
+ ```env
200
+ OPENWEBUI_BASE_URL=http://localhost:8080
201
+ OPENWEBUI_API_KEY=sk-...
202
+ ```
203
+
204
+ 2. **MCP endpoint auth** (optional). Set `OPENWEBUI_MCP_TOKEN=<token>` to make
205
+ the MCP server itself require `Authorization: Bearer <token>` on every
206
+ request. Unset, the endpoint is open to its listeners
207
+
208
+ ## TLS to Open WebUI
209
+
210
+ If Open WebUI is served over https with a certificate the process does not
211
+ trust (self-signed, private/Traefik CA, or a MITM proxy CA), the SDK raises
212
+ `CERTIFICATE_VERIFY_FAILED`. Fix by trusting the right CA, never by
213
+ silently disabling checks unless you must:
214
+
215
+ ```env
216
+ OPENWEBUI_CA_BUNDLE=/path/to/ca.pem # trust a specific PEM CA (covers JSON routes + Socket.IO tool loop)
217
+ OPENWEBUI_SSL_VERIFY=false # skip verification (JSON routes only; not recommended)
218
+ ```
219
+
220
+ The CA bundle path is applied as `SSL_CERT_FILE`, so all Python TLS callers
221
+ (urllib and aiohttp) pick it up. `OPENWEBUI_SSL_VERIFY=false` only relaxes the
222
+ urllib (JSON) routes; the Socket.IO tool loop still verifies, so prefer the CA
223
+ bundle for self-signed servers
224
+
225
+ ## Install
226
+
227
+ Run straight from PyPI, no local checkout needed:
228
+
229
+ ```bash
230
+ uvx openwebui-mcp --help
231
+ ```
232
+
233
+ Or install it as a tool so the `openwebui-mcp` command is always available:
234
+
235
+ ```bash
236
+ uv tool install openwebui-mcp
237
+ openwebui-mcp --help
238
+ ```
239
+
240
+ Requires Python 3.11+
241
+
242
+ Cloning the repo is only needed for development: `uv sync` (creates
243
+ `.venv-docker`) then `uv run openwebui-mcp --help`
244
+
245
+ ## Configure
246
+
247
+ Copy `.env.example` to `.env` or export the variables. Precedence is the first
248
+ defined env var in each alias list
249
+
250
+ | Setting | Env vars (first wins) | Default |
251
+ | --- | --- | --- |
252
+ | Open WebUI URL | `OPENWEBUI_BASE_URL`, `OPENWEBUI_URL`, `OWUI_URL` | required |
253
+ | Open WebUI token | `OPENWEBUI_API_KEY`, `OPENWEBUI_TOKEN`, `OWUI_API_KEY`, `OWUI_TOKEN` | required |
254
+ | Default model for `ask` | `OPENWEBUI_DEFAULT_MODEL`, `OWUI_DEFAULT_MODEL` | none |
255
+ | Enforce default model | `OPENWEBUI_ENFORCE_DEFAULT_MODEL`, `OWUI_ENFORCE_DEFAULT_MODEL` | `false` |
256
+ | `ask` tool description | `OPENWEBUI_ASK_DESCRIPTION`, `OWUI_ASK_DESCRIPTION` | built-in docstring |
257
+ | Server instructions | `OPENWEBUI_INSTRUCTIONS`, `OWUI_INSTRUCTIONS` | none |
258
+ | MCP bearer token | `OPENWEBUI_MCP_TOKEN`, `OWUI_MCP_TOKEN` | none |
259
+ | Transport | `OPENWEBUI_MCP_TRANSPORT` | `stdio` |
260
+ | Chat timeout ms | `OWUI_TIMEOUT_MS` | `120000` |
261
+ | Open WebUI CA bundle | `OPENWEBUI_CA_BUNDLE`, `OWUI_CA_BUNDLE` | none |
262
+ | Skip TLS verify | `OPENWEBUI_SSL_VERIFY`, `OWUI_SSL_VERIFY` | `true` |
263
+
264
+ ## Run
265
+
266
+ ```bash
267
+ uv run openwebui-mcp # stdio (default), for local MCP clients
268
+ uv run openwebui-mcp --transport sse # SSE over HTTP
269
+ uv run openwebui-mcp --transport streamable-http --host 0.0.0.0 --port 8000
270
+ ```
271
+
272
+ ## Development
273
+
274
+ ```bash
275
+ uv run pytest
276
+ uv run pyright src tests
277
+ ```
278
+
279
+ ## Layout
280
+
281
+ - `src/openwebui_mcp/server.py` - FastMCP server, the two tools, TLS apply, static token verifier
282
+ - `src/openwebui_mcp/config.py` - env-driven settings
283
+ - `src/openwebui_mcp/__main__.py` - CLI entry point
284
+ - `skills/owui-proactive-ask/` - agent skill that forces proactive use of `ask`
285
+ - `tests/` - config + server + TLS unit tests, incl. a protocol-level `call_tool` round trip
@@ -0,0 +1,10 @@
1
+ openwebui_mcp/__init__.py,sha256=YFRn-3gatRs3hpLkCgHD9kIOTER39PvhHDpi7vFMOzE,461
2
+ openwebui_mcp/__main__.py,sha256=JaHhP_ts2xRAbsU77CMY_XV813p0tiz-U6ss_ybgiT4,2005
3
+ openwebui_mcp/config.py,sha256=DbzdwS6PRkb4qf-WqdZxwjv85fBXCGqkwAfKXNBlDRI,6753
4
+ openwebui_mcp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ openwebui_mcp/server.py,sha256=pFDf6YBIBNaOPIga-CNNwYAFF87OtFS4m2fyt6TStiY,12480
6
+ openwebui_mcp-0.1.1.dist-info/METADATA,sha256=PoNu9SCEQggqJKymQOGoM8mJ4G6d6Rhov3lhGKL-uY4,9536
7
+ openwebui_mcp-0.1.1.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
8
+ openwebui_mcp-0.1.1.dist-info/entry_points.txt,sha256=i5sNGn-1Zb2XxuLhoJOKVcv5ZO1lponsZUYmpGv8KUE,62
9
+ openwebui_mcp-0.1.1.dist-info/top_level.txt,sha256=veBvD4pdO3N1i6XxeWceI5-xQyyeeXudNFQ_lMoGIFs,14
10
+ openwebui_mcp-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ openwebui-mcp = openwebui_mcp.__main__:main
@@ -0,0 +1 @@
1
+ openwebui_mcp