mcp-embedded-ui 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.
- mcp_embedded_ui/__init__.py +29 -0
- mcp_embedded_ui/html.py +401 -0
- mcp_embedded_ui/py.typed +0 -0
- mcp_embedded_ui/server.py +271 -0
- mcp_embedded_ui-0.1.0.dist-info/METADATA +219 -0
- mcp_embedded_ui-0.1.0.dist-info/RECORD +7 -0
- mcp_embedded_ui-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
|
|
2
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
3
|
+
|
|
4
|
+
from .server import (
|
|
5
|
+
AuthHook,
|
|
6
|
+
CallResult,
|
|
7
|
+
ToolCallHandler,
|
|
8
|
+
ToolsProvider,
|
|
9
|
+
build_mcp_ui_routes,
|
|
10
|
+
build_ui_routes,
|
|
11
|
+
create_app,
|
|
12
|
+
create_mount,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
__version__ = version("mcp-embedded-ui")
|
|
17
|
+
except PackageNotFoundError:
|
|
18
|
+
__version__ = "unknown"
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"AuthHook",
|
|
22
|
+
"CallResult",
|
|
23
|
+
"ToolCallHandler",
|
|
24
|
+
"ToolsProvider",
|
|
25
|
+
"build_mcp_ui_routes",
|
|
26
|
+
"build_ui_routes",
|
|
27
|
+
"create_app",
|
|
28
|
+
"create_mount",
|
|
29
|
+
]
|
mcp_embedded_ui/html.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
"""Self-contained HTML page for the MCP Tool Explorer."""
|
|
2
|
+
|
|
3
|
+
_EXPLORER_HTML_TEMPLATE = """\
|
|
4
|
+
<!DOCTYPE html>
|
|
5
|
+
<html lang="en">
|
|
6
|
+
<head>
|
|
7
|
+
<meta charset="utf-8">
|
|
8
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
9
|
+
<title>{{TITLE}}</title>
|
|
10
|
+
<style>
|
|
11
|
+
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
12
|
+
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, monospace;
|
|
13
|
+
background: #f5f5f5; color: #333; padding: 24px; }
|
|
14
|
+
h1 { font-size: 1.4rem; margin-bottom: 16px; }
|
|
15
|
+
.tool-list { list-style: none; }
|
|
16
|
+
.tool-item { background: #fff; border: 1px solid #ddd; border-radius: 6px;
|
|
17
|
+
margin-bottom: 8px; overflow: hidden; }
|
|
18
|
+
.tool-header { padding: 12px 16px; cursor: pointer; display: flex;
|
|
19
|
+
align-items: flex-start; gap: 8px; }
|
|
20
|
+
.tool-header:hover { background: #fafafa; }
|
|
21
|
+
.tool-toggle { color: #999; font-size: 0.7rem; margin-top: 3px; transition: transform 0.2s; flex-shrink: 0; }
|
|
22
|
+
.tool-item.expanded .tool-toggle { transform: rotate(90deg); }
|
|
23
|
+
.tool-item.expanded { border-color: #888; }
|
|
24
|
+
.tool-summary { flex: 1; }
|
|
25
|
+
.tool-name { font-weight: 600; }
|
|
26
|
+
.tool-desc { color: #666; font-size: 0.9rem; margin-top: 4px; }
|
|
27
|
+
.hint { display: inline-block; background: #e8e8e8; padding: 2px 8px;
|
|
28
|
+
border-radius: 3px; font-size: 0.75rem; margin-right: 4px; }
|
|
29
|
+
.hint-readonly { background: #d4edda; color: #155724; }
|
|
30
|
+
.hint-destructive { background: #f8d7da; color: #721c24; }
|
|
31
|
+
.hint-idempotent { background: #cce5ff; color: #004085; }
|
|
32
|
+
.tool-detail { display: none; padding: 0 16px 16px; border-top: 1px solid #eee; }
|
|
33
|
+
.tool-item.expanded .tool-detail { display: block; }
|
|
34
|
+
.detail-title { font-size: 1.1rem; margin: 12px 0; }
|
|
35
|
+
.schema-label { font-weight: 600; margin-top: 12px; display: block; }
|
|
36
|
+
pre { background: #282c34; color: #abb2bf; padding: 12px; border-radius: 4px;
|
|
37
|
+
overflow-x: auto; font-size: 0.85rem; margin-top: 4px; }
|
|
38
|
+
#loading { color: #888; }
|
|
39
|
+
.try-it { margin-top: 16px; border-top: 1px solid #eee; padding-top: 16px; }
|
|
40
|
+
.try-it h3 { font-size: 0.95rem; margin-bottom: 8px; }
|
|
41
|
+
.input-editor { width: 100%; min-height: 120px; font-family: monospace;
|
|
42
|
+
font-size: 0.85rem; padding: 10px; border: 1px solid #ddd;
|
|
43
|
+
border-radius: 4px; resize: vertical; background: #fafafa; }
|
|
44
|
+
.execute-btn { margin-top: 8px; padding: 8px 20px; background: #4CAF50; color: #fff;
|
|
45
|
+
border: none; border-radius: 4px; cursor: pointer; font-size: 0.9rem;
|
|
46
|
+
font-weight: 600; }
|
|
47
|
+
.execute-btn:hover { background: #45a049; }
|
|
48
|
+
.execute-btn:disabled { background: #ccc; cursor: not-allowed; }
|
|
49
|
+
.result-area { margin-top: 12px; }
|
|
50
|
+
.result-area pre { background: #1a2332; }
|
|
51
|
+
.result-error { color: #f93e3e; }
|
|
52
|
+
.result-success { color: #49cc90; }
|
|
53
|
+
.exec-disabled { color: #888; font-size: 0.85rem; font-style: italic; margin-top: 16px; }
|
|
54
|
+
.auth-bar { display: flex; align-items: center; gap: 8px; margin-bottom: 16px;
|
|
55
|
+
padding: 10px 14px; background: #fff; border: 1px solid #ddd;
|
|
56
|
+
border-radius: 6px; }
|
|
57
|
+
.auth-bar label { font-weight: 600; font-size: 0.85rem; white-space: nowrap; }
|
|
58
|
+
.auth-bar input { flex: 1; font-family: monospace; font-size: 0.82rem;
|
|
59
|
+
padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; }
|
|
60
|
+
.auth-bar .auth-status { font-size: 0.75rem; padding: 2px 8px; border-radius: 3px; }
|
|
61
|
+
.auth-bar .auth-locked { background: #d4edda; color: #155724; }
|
|
62
|
+
.auth-bar .auth-unlocked { background: #f8d7da; color: #721c24; }
|
|
63
|
+
.curl-section { margin-top: 14px; }
|
|
64
|
+
.curl-block { background: #282c34; color: #abb2bf; padding: 12px; padding-right: 60px;
|
|
65
|
+
border-radius: 4px; overflow-x: auto; font-size: 0.82rem;
|
|
66
|
+
white-space: pre-wrap; word-break: break-all; position: relative;
|
|
67
|
+
font-family: monospace; margin-top: 4px; }
|
|
68
|
+
.copy-btn { position: absolute; top: 8px; right: 8px; background: #3a3f4b; color: #999;
|
|
69
|
+
border: 1px solid #555; border-radius: 3px; padding: 2px 10px;
|
|
70
|
+
font-size: 0.72rem; cursor: pointer; }
|
|
71
|
+
.copy-btn:hover { background: #4a4f5b; color: #fff; }
|
|
72
|
+
.resp-header { display: flex; align-items: center; gap: 12px; margin-top: 12px; }
|
|
73
|
+
.resp-tabs { display: inline-flex; }
|
|
74
|
+
.resp-tab { padding: 3px 10px; background: #eee; border: 1px solid #ddd;
|
|
75
|
+
cursor: pointer; font-size: 0.75rem; user-select: none; }
|
|
76
|
+
.resp-tab:first-child { border-radius: 3px 0 0 3px; }
|
|
77
|
+
.resp-tab:last-child { border-radius: 0 3px 3px 0; }
|
|
78
|
+
.resp-tab.active { background: #555; color: #fff; border-color: #555; }
|
|
79
|
+
.resp-pane { display: none; }
|
|
80
|
+
.resp-pane.active { display: block; }
|
|
81
|
+
</style>
|
|
82
|
+
</head>
|
|
83
|
+
<body>
|
|
84
|
+
<h1>{{TITLE}}</h1>
|
|
85
|
+
<div class="auth-bar" id="auth-bar">
|
|
86
|
+
<label for="auth-token">Authorization</label>
|
|
87
|
+
<input type="text" id="auth-token" placeholder="Bearer eyJhbGci...">
|
|
88
|
+
<span class="auth-status auth-unlocked" id="auth-status">No token</span>
|
|
89
|
+
</div>
|
|
90
|
+
<div id="loading">Loading tools...</div>
|
|
91
|
+
<ul class="tool-list" id="tools"></ul>
|
|
92
|
+
<script>
|
|
93
|
+
(function() {
|
|
94
|
+
var base = window.location.pathname.replace(/\\/$/, '');
|
|
95
|
+
var toolsEl = document.getElementById('tools');
|
|
96
|
+
var loadingEl = document.getElementById('loading');
|
|
97
|
+
var authInput = document.getElementById('auth-token');
|
|
98
|
+
var authStatus = document.getElementById('auth-status');
|
|
99
|
+
var executeEnabled = null;
|
|
100
|
+
|
|
101
|
+
function getAuthHeaders() {
|
|
102
|
+
var token = (authInput.value || '').trim();
|
|
103
|
+
if (!token) return {};
|
|
104
|
+
if (token.toLowerCase().indexOf('bearer ') !== 0) token = 'Bearer ' + token;
|
|
105
|
+
return {'Authorization': token};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function updateAuthStatus() {
|
|
109
|
+
var token = (authInput.value || '').trim();
|
|
110
|
+
if (token) {
|
|
111
|
+
authStatus.textContent = 'Token set';
|
|
112
|
+
authStatus.className = 'auth-status auth-locked';
|
|
113
|
+
} else {
|
|
114
|
+
authStatus.textContent = 'No token';
|
|
115
|
+
authStatus.className = 'auth-status auth-unlocked';
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
authInput.addEventListener('input', updateAuthStatus);
|
|
119
|
+
|
|
120
|
+
function esc(s) {
|
|
121
|
+
var d = document.createElement('div');
|
|
122
|
+
d.appendChild(document.createTextNode(s));
|
|
123
|
+
return d.innerHTML;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function defaultFromSchema(schema) {
|
|
127
|
+
if (!schema || !schema.properties) return {};
|
|
128
|
+
var result = {};
|
|
129
|
+
var props = schema.properties;
|
|
130
|
+
for (var key in props) {
|
|
131
|
+
if (!props.hasOwnProperty(key)) continue;
|
|
132
|
+
var t = props[key].type;
|
|
133
|
+
if (props[key]['default'] != null) {
|
|
134
|
+
result[key] = props[key]['default'];
|
|
135
|
+
} else if (t === 'string') {
|
|
136
|
+
result[key] = '';
|
|
137
|
+
} else if (t === 'number' || t === 'integer') {
|
|
138
|
+
result[key] = 0;
|
|
139
|
+
} else if (t === 'boolean') {
|
|
140
|
+
result[key] = false;
|
|
141
|
+
} else if (t === 'array') {
|
|
142
|
+
result[key] = [];
|
|
143
|
+
} else if (t === 'object') {
|
|
144
|
+
result[key] = {};
|
|
145
|
+
} else {
|
|
146
|
+
result[key] = null;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return result;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function hintsHtml(annotations) {
|
|
153
|
+
if (!annotations) return '';
|
|
154
|
+
var parts = [];
|
|
155
|
+
if (annotations.readOnlyHint) parts.push('<span class="hint hint-readonly">readOnly</span>');
|
|
156
|
+
if (annotations.destructiveHint) parts.push('<span class="hint hint-destructive">destructive</span>');
|
|
157
|
+
if (annotations.idempotentHint) parts.push('<span class="hint hint-idempotent">idempotent</span>');
|
|
158
|
+
if (annotations.openWorldHint === false) parts.push('<span class="hint">closedWorld</span>');
|
|
159
|
+
return parts.join('');
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Fetch meta info to determine execution status
|
|
163
|
+
fetch(base + '/meta').then(function(r) { return r.json(); }).then(function(meta) {
|
|
164
|
+
executeEnabled = meta.allow_execute;
|
|
165
|
+
}).catch(function() {});
|
|
166
|
+
|
|
167
|
+
fetch(base + '/tools', {headers: getAuthHeaders()})
|
|
168
|
+
.then(function(r) { return r.json(); })
|
|
169
|
+
.then(function(tools) {
|
|
170
|
+
loadingEl.style.display = 'none';
|
|
171
|
+
tools.forEach(function(t) {
|
|
172
|
+
var li = document.createElement('li');
|
|
173
|
+
li.className = 'tool-item';
|
|
174
|
+
li.setAttribute('data-tool', t.name);
|
|
175
|
+
li.innerHTML =
|
|
176
|
+
'<div class="tool-header">' +
|
|
177
|
+
'<span class="tool-toggle">▶</span>' +
|
|
178
|
+
'<div class="tool-summary">' +
|
|
179
|
+
'<span class="tool-name">' + esc(t.name) + '</span> ' +
|
|
180
|
+
hintsHtml(t.annotations) +
|
|
181
|
+
'<div class="tool-desc">' + esc(t.description || '') + '</div>' +
|
|
182
|
+
'</div>' +
|
|
183
|
+
'</div>' +
|
|
184
|
+
'<div class="tool-detail"></div>';
|
|
185
|
+
li.querySelector('.tool-header').onclick = function() { toggleTool(li, t.name); };
|
|
186
|
+
toolsEl.appendChild(li);
|
|
187
|
+
});
|
|
188
|
+
})
|
|
189
|
+
.catch(function(e) { loadingEl.textContent = 'Error: ' + e; });
|
|
190
|
+
|
|
191
|
+
function toggleTool(li, name) {
|
|
192
|
+
if (li.classList.contains('expanded')) {
|
|
193
|
+
li.classList.remove('expanded');
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
// Collapse any other expanded tool
|
|
197
|
+
var prev = toolsEl.querySelector('.tool-item.expanded');
|
|
198
|
+
if (prev && prev !== li) prev.classList.remove('expanded');
|
|
199
|
+
li.classList.add('expanded');
|
|
200
|
+
var detailEl = li.querySelector('.tool-detail');
|
|
201
|
+
// Load detail if not yet loaded
|
|
202
|
+
if (!detailEl.getAttribute('data-loaded')) {
|
|
203
|
+
loadDetail(li, name);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function loadDetail(li, name) {
|
|
208
|
+
var detailEl = li.querySelector('.tool-detail');
|
|
209
|
+
detailEl.innerHTML = '<p style="color:#888;padding-top:12px">Loading...</p>';
|
|
210
|
+
fetch(base + '/tools/' + encodeURIComponent(name), {headers: getAuthHeaders()})
|
|
211
|
+
.then(function(r) { return r.json(); })
|
|
212
|
+
.then(function(d) {
|
|
213
|
+
detailEl.setAttribute('data-loaded', '1');
|
|
214
|
+
var html =
|
|
215
|
+
'<span class="schema-label">Input Schema</span>' +
|
|
216
|
+
'<pre>' + esc(JSON.stringify(d.inputSchema, null, 2)) + '</pre>';
|
|
217
|
+
|
|
218
|
+
if (d.annotations) {
|
|
219
|
+
html += '<span class="schema-label">Annotations</span>' +
|
|
220
|
+
'<pre>' + esc(JSON.stringify(d.annotations, null, 2)) + '</pre>';
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
html += '<div class="try-it">' +
|
|
224
|
+
'<h3>Try it</h3>' +
|
|
225
|
+
'<textarea class="input-editor">' +
|
|
226
|
+
esc(JSON.stringify(defaultFromSchema(d.inputSchema), null, 2)) +
|
|
227
|
+
'</textarea>' +
|
|
228
|
+
'<button class="execute-btn">Execute</button>' +
|
|
229
|
+
'<div class="result-area"></div>' +
|
|
230
|
+
'</div>';
|
|
231
|
+
|
|
232
|
+
detailEl.innerHTML = html;
|
|
233
|
+
|
|
234
|
+
detailEl.querySelector('.execute-btn').onclick = function() {
|
|
235
|
+
execTool(li, d.name);
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
if (executeEnabled === false) {
|
|
239
|
+
var tryIt = detailEl.querySelector('.try-it');
|
|
240
|
+
if (tryIt) tryIt.innerHTML =
|
|
241
|
+
'<p class="exec-disabled">' +
|
|
242
|
+
'Tool execution is disabled. ' +
|
|
243
|
+
'Launch with --allow-execute to enable.</p>';
|
|
244
|
+
}
|
|
245
|
+
})
|
|
246
|
+
.catch(function(e) {
|
|
247
|
+
detailEl.setAttribute('data-loaded', '1');
|
|
248
|
+
detailEl.innerHTML = '<p class="result-error" style="padding-top:12px">' +
|
|
249
|
+
'Failed to load tool details: ' + esc(e.message) + '</p>';
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function execTool(li, name) {
|
|
254
|
+
var detailEl = li.querySelector('.tool-detail');
|
|
255
|
+
var btn = detailEl.querySelector('.execute-btn');
|
|
256
|
+
var editor = detailEl.querySelector('.input-editor');
|
|
257
|
+
var resultArea = detailEl.querySelector('.result-area');
|
|
258
|
+
|
|
259
|
+
var inputText = editor.value.trim();
|
|
260
|
+
var inputs;
|
|
261
|
+
try {
|
|
262
|
+
inputs = inputText ? JSON.parse(inputText) : {};
|
|
263
|
+
} catch (e) {
|
|
264
|
+
resultArea.innerHTML = '<p class="result-error">Invalid JSON: ' + esc(e.message) + '</p>';
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
btn.disabled = true;
|
|
269
|
+
btn.textContent = 'Executing...';
|
|
270
|
+
resultArea.innerHTML = '';
|
|
271
|
+
|
|
272
|
+
var bodyStr = JSON.stringify(inputs);
|
|
273
|
+
var callUrl = window.location.origin + base + '/tools/' + encodeURIComponent(name) + '/call';
|
|
274
|
+
var curlBody = bodyStr.replace(/'/g, "'\\\\''" );
|
|
275
|
+
var authToken = (authInput.value || '').trim();
|
|
276
|
+
var curlLines = ["curl -X POST '" + callUrl + "' \\\\"];
|
|
277
|
+
curlLines.push(" -H 'Content-Type: application/json' \\\\");
|
|
278
|
+
if (authToken) {
|
|
279
|
+
var bearerVal = authToken.toLowerCase().indexOf('bearer ') === 0 ? authToken : 'Bearer ' + authToken;
|
|
280
|
+
curlLines.push(" -H 'Authorization: " + bearerVal + "' \\\\");
|
|
281
|
+
}
|
|
282
|
+
curlLines.push(" -d '" + curlBody + "'");
|
|
283
|
+
var curlCmd = curlLines.join("\\n");
|
|
284
|
+
|
|
285
|
+
var fetchHeaders = Object.assign({'Content-Type': 'application/json'}, getAuthHeaders());
|
|
286
|
+
fetch(base + '/tools/' + encodeURIComponent(name) + '/call', {
|
|
287
|
+
method: 'POST',
|
|
288
|
+
headers: fetchHeaders,
|
|
289
|
+
body: bodyStr
|
|
290
|
+
})
|
|
291
|
+
.then(function(r) {
|
|
292
|
+
if (r.status === 403) {
|
|
293
|
+
executeEnabled = false;
|
|
294
|
+
var tryIt = detailEl.querySelector('.try-it');
|
|
295
|
+
if (tryIt) tryIt.innerHTML =
|
|
296
|
+
'<p class="exec-disabled">' +
|
|
297
|
+
'Tool execution is disabled. ' +
|
|
298
|
+
'Launch with --allow-execute to enable.</p>';
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
if (r.status === 401) {
|
|
302
|
+
btn.disabled = false;
|
|
303
|
+
btn.textContent = 'Execute';
|
|
304
|
+
resultArea.innerHTML =
|
|
305
|
+
'<p class="result-error">401 Unauthorized \\u2014 ' +
|
|
306
|
+
'enter a valid Bearer token in the Authorization field above.</p>';
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
return r.json().then(function(data) { return {status: r.status, data: data}; });
|
|
310
|
+
})
|
|
311
|
+
.then(function(result) {
|
|
312
|
+
if (!result) return;
|
|
313
|
+
btn.disabled = false;
|
|
314
|
+
btn.textContent = 'Execute';
|
|
315
|
+
var data = result.data;
|
|
316
|
+
var html = '';
|
|
317
|
+
|
|
318
|
+
html += '<div class="curl-section">' +
|
|
319
|
+
'<span class="schema-label">cURL</span>' +
|
|
320
|
+
'<div class="curl-block"><code class="curl-cmd">' + esc(curlCmd) +
|
|
321
|
+
'</code><button class="copy-btn">Copy</button></div></div>';
|
|
322
|
+
|
|
323
|
+
if (data.isError) {
|
|
324
|
+
var errText = (data.content || []).map(function(c) { return c.text || ''; }).join('\\n');
|
|
325
|
+
html += '<span class="schema-label result-error">Response — Error</span>' +
|
|
326
|
+
'<pre>' + esc(errText) + '</pre>';
|
|
327
|
+
} else {
|
|
328
|
+
var texts = (data.content || []).filter(function(c) { return c.type === 'text'; });
|
|
329
|
+
var display = texts.map(function(c) {
|
|
330
|
+
try { return JSON.parse(c.text); } catch(e) { return c.text; }
|
|
331
|
+
});
|
|
332
|
+
var output = display.length === 1 ? display[0] : display;
|
|
333
|
+
var friendlyJson = JSON.stringify(output, null, 2);
|
|
334
|
+
var rawJson = JSON.stringify(data, null, 2);
|
|
335
|
+
|
|
336
|
+
html += '<div class="resp-header">' +
|
|
337
|
+
'<span class="schema-label result-success" style="margin:0">Response</span>' +
|
|
338
|
+
'<span class="resp-tabs">' +
|
|
339
|
+
'<span class="resp-tab active" data-tab="friendly">Result</span>' +
|
|
340
|
+
'<span class="resp-tab" data-tab="raw">Raw MCP</span>' +
|
|
341
|
+
'</span></div>' +
|
|
342
|
+
'<pre class="resp-pane active" data-pane="friendly">' + esc(friendlyJson) + '</pre>' +
|
|
343
|
+
'<pre class="resp-pane" data-pane="raw">' + esc(rawJson) + '</pre>';
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
resultArea.innerHTML = html;
|
|
347
|
+
|
|
348
|
+
var copyBtn = resultArea.querySelector('.copy-btn');
|
|
349
|
+
if (copyBtn) {
|
|
350
|
+
copyBtn.onclick = function() {
|
|
351
|
+
var cmd = resultArea.querySelector('.curl-cmd');
|
|
352
|
+
if (cmd && navigator.clipboard) {
|
|
353
|
+
navigator.clipboard.writeText(cmd.textContent).then(function() {
|
|
354
|
+
copyBtn.textContent = 'Copied!';
|
|
355
|
+
setTimeout(function() { copyBtn.textContent = 'Copy'; }, 1500);
|
|
356
|
+
}).catch(function() {
|
|
357
|
+
copyBtn.textContent = 'Failed';
|
|
358
|
+
setTimeout(function() { copyBtn.textContent = 'Copy'; }, 1500);
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
var tabs = resultArea.querySelectorAll('.resp-tab');
|
|
364
|
+
for (var i = 0; i < tabs.length; i++) {
|
|
365
|
+
(function(tab) {
|
|
366
|
+
tab.onclick = function() {
|
|
367
|
+
var target = tab.getAttribute('data-tab');
|
|
368
|
+
var allTabs = resultArea.querySelectorAll('.resp-tab');
|
|
369
|
+
var allPanes = resultArea.querySelectorAll('.resp-pane');
|
|
370
|
+
for (var j = 0; j < allTabs.length; j++) {
|
|
371
|
+
allTabs[j].className = allTabs[j].getAttribute('data-tab') === target
|
|
372
|
+
? 'resp-tab active' : 'resp-tab';
|
|
373
|
+
}
|
|
374
|
+
for (var j = 0; j < allPanes.length; j++) {
|
|
375
|
+
allPanes[j].className = allPanes[j].getAttribute('data-pane') === target
|
|
376
|
+
? 'resp-pane active' : 'resp-pane';
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
})(tabs[i]);
|
|
380
|
+
}
|
|
381
|
+
})
|
|
382
|
+
.catch(function(e) {
|
|
383
|
+
btn.disabled = false;
|
|
384
|
+
btn.textContent = 'Execute';
|
|
385
|
+
resultArea.innerHTML = '<p class="result-error">Request failed: ' + esc(e.message) + '</p>';
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
})();
|
|
389
|
+
</script>
|
|
390
|
+
</body>
|
|
391
|
+
</html>
|
|
392
|
+
"""
|
|
393
|
+
|
|
394
|
+
_DEFAULT_TITLE = "MCP Tool Explorer"
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def render_explorer_html(title: str = _DEFAULT_TITLE) -> str:
|
|
398
|
+
"""Render the explorer HTML page with the given title."""
|
|
399
|
+
from html import escape
|
|
400
|
+
|
|
401
|
+
return _EXPLORER_HTML_TEMPLATE.replace("{{TITLE}}", escape(title))
|
mcp_embedded_ui/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""Core route generation and ASGI app factory for mcp-embedded-ui."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
import logging
|
|
7
|
+
import warnings
|
|
8
|
+
from contextlib import AbstractAsyncContextManager, AbstractContextManager
|
|
9
|
+
from typing import Any, Awaitable, Callable, TypedDict, Union
|
|
10
|
+
|
|
11
|
+
from starlette.applications import Starlette
|
|
12
|
+
from starlette.requests import Request
|
|
13
|
+
from starlette.responses import HTMLResponse, JSONResponse, Response
|
|
14
|
+
from starlette.routing import Mount, Route
|
|
15
|
+
from starlette.types import ASGIApp
|
|
16
|
+
|
|
17
|
+
from .html import render_explorer_html
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# ---------------------------------------------------------------------------
|
|
23
|
+
# Public types
|
|
24
|
+
# ---------------------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
class CallResult(TypedDict):
|
|
27
|
+
content: list[dict[str, Any]]
|
|
28
|
+
isError: bool
|
|
29
|
+
_meta: dict[str, Any] | None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# Any async callable matching: (name, args) -> (content, is_error, trace_id)
|
|
33
|
+
ToolCallHandler = Callable[
|
|
34
|
+
[str, dict[str, Any]],
|
|
35
|
+
Awaitable[tuple[list[dict[str, Any]], bool, str | None]],
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
# Auth hook can return either a sync or async context manager
|
|
39
|
+
AuthHook = Callable[
|
|
40
|
+
[Request],
|
|
41
|
+
Union[AbstractContextManager[Any], AbstractAsyncContextManager[Any]],
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
# Tools can be a static list, a sync callable, or an async callable
|
|
45
|
+
ToolsProvider = Union[
|
|
46
|
+
list[Any],
|
|
47
|
+
Callable[[], list[Any]],
|
|
48
|
+
Callable[[], Awaitable[list[Any]]],
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# ---------------------------------------------------------------------------
|
|
53
|
+
# Internal helpers
|
|
54
|
+
# ---------------------------------------------------------------------------
|
|
55
|
+
|
|
56
|
+
async def _resolve_tools(tools: ToolsProvider) -> list[Any]:
|
|
57
|
+
"""Resolve a ToolsProvider into a concrete list of tools."""
|
|
58
|
+
if isinstance(tools, list):
|
|
59
|
+
return tools
|
|
60
|
+
result = tools()
|
|
61
|
+
if inspect.isawaitable(result):
|
|
62
|
+
return await result
|
|
63
|
+
return result # type: ignore[return-value]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _make_serializable(obj: Any) -> Any:
|
|
67
|
+
"""Convert common model types to JSON-serializable dicts."""
|
|
68
|
+
if hasattr(obj, "model_dump"):
|
|
69
|
+
return obj.model_dump(exclude_none=True)
|
|
70
|
+
if hasattr(obj, "dict"):
|
|
71
|
+
return obj.dict(exclude_none=True)
|
|
72
|
+
if isinstance(obj, dict):
|
|
73
|
+
return {k: _make_serializable(v) for k, v in obj.items()}
|
|
74
|
+
return obj
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _tool_summary(tool: Any) -> dict[str, Any]:
|
|
78
|
+
"""Return a summary dict for a tool."""
|
|
79
|
+
result: dict[str, Any] = {
|
|
80
|
+
"name": getattr(tool, "name", "unknown"),
|
|
81
|
+
"description": getattr(tool, "description", ""),
|
|
82
|
+
}
|
|
83
|
+
annotations = _make_serializable(getattr(tool, "annotations", None))
|
|
84
|
+
if annotations:
|
|
85
|
+
result["annotations"] = annotations
|
|
86
|
+
return result
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _tool_detail(tool: Any) -> dict[str, Any]:
|
|
90
|
+
"""Return a full detail dict for a tool."""
|
|
91
|
+
result: dict[str, Any] = {
|
|
92
|
+
"name": getattr(tool, "name", "unknown"),
|
|
93
|
+
"description": getattr(tool, "description", ""),
|
|
94
|
+
"inputSchema": _make_serializable(getattr(tool, "inputSchema", {})),
|
|
95
|
+
}
|
|
96
|
+
annotations = _make_serializable(getattr(tool, "annotations", None))
|
|
97
|
+
if annotations:
|
|
98
|
+
result["annotations"] = annotations
|
|
99
|
+
return result
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
async def _resolve_tools_by_name(
|
|
103
|
+
tools: ToolsProvider,
|
|
104
|
+
) -> tuple[list[Any], dict[str, Any]]:
|
|
105
|
+
"""Resolve tools and build a name->tool lookup dict."""
|
|
106
|
+
tool_list = await _resolve_tools(tools)
|
|
107
|
+
by_name = {getattr(t, "name", ""): t for t in tool_list}
|
|
108
|
+
return tool_list, by_name
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# ---------------------------------------------------------------------------
|
|
112
|
+
# Route builder (low-level)
|
|
113
|
+
# ---------------------------------------------------------------------------
|
|
114
|
+
|
|
115
|
+
def build_ui_routes(
|
|
116
|
+
tools: ToolsProvider,
|
|
117
|
+
handle_call: ToolCallHandler,
|
|
118
|
+
*,
|
|
119
|
+
allow_execute: bool = True,
|
|
120
|
+
auth_hook: AuthHook | None = None,
|
|
121
|
+
title: str = "MCP Tool Explorer",
|
|
122
|
+
) -> list[Route]:
|
|
123
|
+
"""Build Starlette routes for the MCP Embedded UI.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
tools: MCP Tool objects (list, sync callable, or async callable).
|
|
127
|
+
Each tool must have ``.name``, ``.description``, ``.inputSchema``.
|
|
128
|
+
handle_call: Async callback for tool execution:
|
|
129
|
+
``(name, args) -> (content, is_error, trace_id)``.
|
|
130
|
+
allow_execute: Enable/disable tool execution via UI.
|
|
131
|
+
auth_hook: Optional hook that receives a ``Request`` and returns a
|
|
132
|
+
context manager (sync or async). Raise inside to reject with
|
|
133
|
+
401. Use your own ``ContextVar`` to propagate identity.
|
|
134
|
+
title: Page title shown in the browser tab and heading.
|
|
135
|
+
"""
|
|
136
|
+
html_page = render_explorer_html(title)
|
|
137
|
+
|
|
138
|
+
async def explorer_page(request: Request) -> HTMLResponse:
|
|
139
|
+
return HTMLResponse(html_page)
|
|
140
|
+
|
|
141
|
+
async def meta(request: Request) -> JSONResponse:
|
|
142
|
+
return JSONResponse({
|
|
143
|
+
"title": title,
|
|
144
|
+
"allow_execute": allow_execute,
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
async def list_tools(request: Request) -> JSONResponse:
|
|
148
|
+
tool_list = await _resolve_tools(tools)
|
|
149
|
+
return JSONResponse([_tool_summary(t) for t in tool_list])
|
|
150
|
+
|
|
151
|
+
async def tool_detail_endpoint(request: Request) -> Response:
|
|
152
|
+
name = request.path_params["name"]
|
|
153
|
+
_, by_name = await _resolve_tools_by_name(tools)
|
|
154
|
+
tool = by_name.get(name)
|
|
155
|
+
if tool is None:
|
|
156
|
+
return JSONResponse({"error": f"Tool not found: {name}"}, status_code=404)
|
|
157
|
+
return JSONResponse(_tool_detail(tool))
|
|
158
|
+
|
|
159
|
+
async def call_tool(request: Request) -> Response:
|
|
160
|
+
if not allow_execute:
|
|
161
|
+
return JSONResponse({"error": "Tool execution is disabled."}, status_code=403)
|
|
162
|
+
|
|
163
|
+
name = request.path_params["name"]
|
|
164
|
+
_, by_name = await _resolve_tools_by_name(tools)
|
|
165
|
+
tool = by_name.get(name)
|
|
166
|
+
if tool is None:
|
|
167
|
+
return JSONResponse({"error": f"Tool not found: {name}"}, status_code=404)
|
|
168
|
+
|
|
169
|
+
try:
|
|
170
|
+
body = await request.json()
|
|
171
|
+
except Exception:
|
|
172
|
+
body = {}
|
|
173
|
+
|
|
174
|
+
if auth_hook:
|
|
175
|
+
try:
|
|
176
|
+
cm = auth_hook(request)
|
|
177
|
+
if isinstance(cm, AbstractAsyncContextManager):
|
|
178
|
+
async with cm:
|
|
179
|
+
return await _do_call(name, body, handle_call)
|
|
180
|
+
else:
|
|
181
|
+
with cm:
|
|
182
|
+
return await _do_call(name, body, handle_call)
|
|
183
|
+
except Exception as e:
|
|
184
|
+
logger.warning("Auth hook failed for tool %s: %s", name, e)
|
|
185
|
+
return JSONResponse(
|
|
186
|
+
{"error": "Unauthorized"},
|
|
187
|
+
status_code=401,
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
return await _do_call(name, body, handle_call)
|
|
191
|
+
|
|
192
|
+
async def _do_call(
|
|
193
|
+
name: str, body: dict, handler: ToolCallHandler
|
|
194
|
+
) -> JSONResponse:
|
|
195
|
+
try:
|
|
196
|
+
content, is_error, trace_id = await handler(name, body)
|
|
197
|
+
result: dict[str, Any] = {"content": content, "isError": is_error}
|
|
198
|
+
if trace_id:
|
|
199
|
+
result["_meta"] = {"_trace_id": trace_id}
|
|
200
|
+
return JSONResponse(result, status_code=500 if is_error else 200)
|
|
201
|
+
except Exception as exc:
|
|
202
|
+
logger.error("UI call_tool error for %s: %s", name, exc)
|
|
203
|
+
return JSONResponse(
|
|
204
|
+
{"content": [{"type": "text", "text": str(exc)}], "isError": True},
|
|
205
|
+
status_code=500,
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
return [
|
|
209
|
+
Route("/", endpoint=explorer_page, methods=["GET"]),
|
|
210
|
+
Route("/meta", endpoint=meta, methods=["GET"]),
|
|
211
|
+
Route("/tools", endpoint=list_tools, methods=["GET"]),
|
|
212
|
+
Route("/tools/{name:path}/call", endpoint=call_tool, methods=["POST"]),
|
|
213
|
+
Route("/tools/{name:path}", endpoint=tool_detail_endpoint, methods=["GET"]),
|
|
214
|
+
]
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
# ---------------------------------------------------------------------------
|
|
218
|
+
# High-level factories
|
|
219
|
+
# ---------------------------------------------------------------------------
|
|
220
|
+
|
|
221
|
+
def create_app(
|
|
222
|
+
tools: ToolsProvider,
|
|
223
|
+
handle_call: ToolCallHandler,
|
|
224
|
+
**kwargs: Any,
|
|
225
|
+
) -> ASGIApp:
|
|
226
|
+
"""Create a standalone ASGI application for the MCP Embedded UI.
|
|
227
|
+
|
|
228
|
+
This is the universal entry point — mount in any ASGI-compatible
|
|
229
|
+
framework (Starlette, FastAPI, Django, aiohttp via adapter, etc.).
|
|
230
|
+
|
|
231
|
+
All keyword arguments are forwarded to :func:`build_ui_routes`.
|
|
232
|
+
"""
|
|
233
|
+
routes = build_ui_routes(tools, handle_call, **kwargs)
|
|
234
|
+
return Starlette(routes=routes)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def create_mount(
|
|
238
|
+
prefix: str = "/explorer",
|
|
239
|
+
*,
|
|
240
|
+
tools: ToolsProvider,
|
|
241
|
+
handle_call: ToolCallHandler,
|
|
242
|
+
**kwargs: Any,
|
|
243
|
+
) -> Mount:
|
|
244
|
+
"""Create a Starlette ``Mount`` for embedding the UI under a URL prefix.
|
|
245
|
+
|
|
246
|
+
Convenience wrapper for Starlette/FastAPI apps::
|
|
247
|
+
|
|
248
|
+
app.routes.append(create_mount(tools=tools, handle_call=handler))
|
|
249
|
+
|
|
250
|
+
All keyword arguments are forwarded to :func:`build_ui_routes`.
|
|
251
|
+
"""
|
|
252
|
+
routes = build_ui_routes(tools, handle_call, **kwargs)
|
|
253
|
+
return Mount(prefix, routes=routes)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
# ---------------------------------------------------------------------------
|
|
257
|
+
# Backward compatibility
|
|
258
|
+
# ---------------------------------------------------------------------------
|
|
259
|
+
|
|
260
|
+
def build_mcp_ui_routes(
|
|
261
|
+
tools: ToolsProvider,
|
|
262
|
+
handle_call: ToolCallHandler,
|
|
263
|
+
**kwargs: Any,
|
|
264
|
+
) -> list[Route]:
|
|
265
|
+
"""Deprecated: use :func:`build_ui_routes` instead."""
|
|
266
|
+
warnings.warn(
|
|
267
|
+
"build_mcp_ui_routes is deprecated, use build_ui_routes instead",
|
|
268
|
+
DeprecationWarning,
|
|
269
|
+
stacklevel=2,
|
|
270
|
+
)
|
|
271
|
+
return build_ui_routes(tools, handle_call, **kwargs)
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mcp-embedded-ui
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A lightweight, minimal-dependency embedded Web UI for any MCP Server.
|
|
5
|
+
Project-URL: Homepage, https://aipartnerup.com
|
|
6
|
+
Project-URL: Documentation, https://github.com/aipartnerup/mcp-embedded-ui
|
|
7
|
+
Project-URL: Repository, https://github.com/aipartnerup/mcp-embedded-ui-python
|
|
8
|
+
Project-URL: Issues, https://github.com/aipartnerup/mcp-embedded-ui-python/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/aipartnerup/mcp-embedded-ui-python/blob/main/CHANGELOG.md
|
|
10
|
+
Author-email: aipartnerup <team@aipartnerup.com>
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
Keywords: asgi,explorer,fastapi,mcp,model-context-protocol,starlette,tools,ui
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Requires-Dist: starlette>=0.14.0
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: fastapi; extra == 'dev'
|
|
27
|
+
Requires-Dist: httpx; extra == 'dev'
|
|
28
|
+
Requires-Dist: mypy>=1.0; extra == 'dev'
|
|
29
|
+
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
|
|
30
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
31
|
+
Requires-Dist: ruff>=0.1; extra == 'dev'
|
|
32
|
+
Requires-Dist: uvicorn; extra == 'dev'
|
|
33
|
+
Description-Content-Type: text/markdown
|
|
34
|
+
|
|
35
|
+
# mcp-embedded-ui (Python)
|
|
36
|
+
|
|
37
|
+
The Python implementation of [mcp-embedded-ui](https://github.com/aipartnerup/mcp-embedded-ui) — a browser-based tool explorer for any [MCP](https://modelcontextprotocol.io/) (Model Context Protocol) server.
|
|
38
|
+
|
|
39
|
+
## What is this?
|
|
40
|
+
|
|
41
|
+
If you build an MCP server in Python, your users interact with tools through raw JSON — no visual feedback, no schema browser, no quick way to test. This library adds a full browser UI to your server with **one import and one mount**.
|
|
42
|
+
|
|
43
|
+
```
|
|
44
|
+
┌───────────────────────────────────┐
|
|
45
|
+
│ Browser │
|
|
46
|
+
│ Tool list → Schema → Try it │
|
|
47
|
+
└──────────────┬────────────────────┘
|
|
48
|
+
│ HTTP / JSON
|
|
49
|
+
┌──────────────▼────────────────────┐
|
|
50
|
+
│ Your Python MCP Server │
|
|
51
|
+
│ + mcp-embedded-ui │
|
|
52
|
+
│ (FastAPI / Starlette / ASGI) │
|
|
53
|
+
└───────────────────────────────────┘
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## What does the UI provide?
|
|
57
|
+
|
|
58
|
+
- **Tool list** — browse all registered tools with descriptions and annotation badges
|
|
59
|
+
- **Schema inspector** — expand any tool to view its full JSON Schema (`inputSchema`)
|
|
60
|
+
- **Try-it console** — type JSON arguments, execute the tool, see results instantly
|
|
61
|
+
- **cURL export** — copy a ready-made cURL command for any execution
|
|
62
|
+
- **Auth support** — enter a Bearer token in the UI, sent with all requests
|
|
63
|
+
|
|
64
|
+
No build step. No CDN. No external dependencies. The entire UI is a single self-contained HTML page embedded in the package.
|
|
65
|
+
|
|
66
|
+
## Install
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
pip install mcp-embedded-ui
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Requires Python 3.10+ and [Starlette](https://www.starlette.io/) >= 0.35.
|
|
73
|
+
|
|
74
|
+
## Quick Start
|
|
75
|
+
|
|
76
|
+
### FastAPI / Starlette
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from fastapi import FastAPI
|
|
80
|
+
from mcp_embedded_ui import create_mount
|
|
81
|
+
|
|
82
|
+
app = FastAPI()
|
|
83
|
+
|
|
84
|
+
# Mount at /explorer (default)
|
|
85
|
+
app.routes.append(create_mount(tools=my_tools, handle_call=my_handler))
|
|
86
|
+
|
|
87
|
+
# Or specify a custom prefix
|
|
88
|
+
app.routes.append(create_mount("/mcp-ui", tools=my_tools, handle_call=my_handler))
|
|
89
|
+
|
|
90
|
+
# Visit http://localhost:8000/explorer/
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### Any ASGI framework
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
from mcp_embedded_ui import create_app
|
|
97
|
+
|
|
98
|
+
# Returns a standard ASGI app — mount in any ASGI-compatible framework
|
|
99
|
+
ui_app = create_app(tools=my_tools, handle_call=my_handler)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Full working example
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from fastapi import FastAPI
|
|
106
|
+
from mcp_embedded_ui import create_mount
|
|
107
|
+
|
|
108
|
+
# 1. Define your tools (any object with .name, .description, .inputSchema)
|
|
109
|
+
class MyTool:
|
|
110
|
+
def __init__(self, name, description, input_schema):
|
|
111
|
+
self.name = name
|
|
112
|
+
self.description = description
|
|
113
|
+
self.inputSchema = input_schema
|
|
114
|
+
|
|
115
|
+
tools = [
|
|
116
|
+
MyTool("greet", "Say hello", {
|
|
117
|
+
"type": "object",
|
|
118
|
+
"properties": {"name": {"type": "string"}},
|
|
119
|
+
}),
|
|
120
|
+
]
|
|
121
|
+
|
|
122
|
+
# 2. Define a handler: (name, args) -> (content, is_error, trace_id)
|
|
123
|
+
async def handle_call(name, args):
|
|
124
|
+
if name == "greet":
|
|
125
|
+
return [{"type": "text", "text": f"Hello, {args.get('name', 'world')}!"}], False, None
|
|
126
|
+
return [{"type": "text", "text": f"Unknown tool: {name}"}], True, None
|
|
127
|
+
|
|
128
|
+
# 3. Mount the UI
|
|
129
|
+
app = FastAPI()
|
|
130
|
+
app.routes.append(create_mount(tools=tools, handle_call=handle_call))
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### Dynamic tools
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
# Sync callable — re-evaluated on every request
|
|
137
|
+
def get_tools():
|
|
138
|
+
return registry.list_tools()
|
|
139
|
+
|
|
140
|
+
# Async callable
|
|
141
|
+
async def get_tools():
|
|
142
|
+
return await registry.async_list_tools()
|
|
143
|
+
|
|
144
|
+
app = create_app(tools=get_tools, handle_call=my_handler)
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## API
|
|
148
|
+
|
|
149
|
+
### Three-tier API
|
|
150
|
+
|
|
151
|
+
| Function | Returns | Use case |
|
|
152
|
+
|----------|---------|----------|
|
|
153
|
+
| `create_mount(prefix, *, tools, handle_call, **config)` | `Mount` | FastAPI / Starlette — mount under a URL prefix |
|
|
154
|
+
| `create_app(tools, handle_call, **config)` | `ASGIApp` | Any ASGI framework — standalone app |
|
|
155
|
+
| `build_ui_routes(tools, handle_call, **config)` | `list[Route]` | Power users — fine-grained route control |
|
|
156
|
+
|
|
157
|
+
### Parameters
|
|
158
|
+
|
|
159
|
+
| Parameter | Type | Default | Description |
|
|
160
|
+
|-----------|------|---------|-------------|
|
|
161
|
+
| `tools` | `list \| Callable \| AsyncCallable` | _required_ | MCP Tool objects (`.name`, `.description`, `.inputSchema`) |
|
|
162
|
+
| `handle_call` | `ToolCallHandler` | _required_ | `async (name, args) -> (content, is_error, trace_id)` |
|
|
163
|
+
| `allow_execute` | `bool` | `True` | Enable/disable tool execution (enforced server-side) |
|
|
164
|
+
| `auth_hook` | `AuthHook \| None` | `None` | Sync/async context manager factory for auth |
|
|
165
|
+
| `title` | `str` | `"MCP Tool Explorer"` | Page title (HTML-escaped automatically) |
|
|
166
|
+
|
|
167
|
+
### Auth Hook
|
|
168
|
+
|
|
169
|
+
The `auth_hook` receives a Starlette `Request` and returns a context manager (sync or async). Raise inside to reject with 401. The error response is always `{"error": "Unauthorized"}` — internal details are never leaked.
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
from contextlib import contextmanager
|
|
173
|
+
|
|
174
|
+
@contextmanager
|
|
175
|
+
def my_auth(request):
|
|
176
|
+
token = request.headers.get("Authorization")
|
|
177
|
+
if not valid(token):
|
|
178
|
+
raise ValueError("Bad token")
|
|
179
|
+
my_identity_var.set(decode(token))
|
|
180
|
+
yield
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Auth only guards `POST /tools/{name}/call`. Discovery endpoints (`GET /tools`, `GET /tools/{name}`, `GET /meta`) are always public.
|
|
184
|
+
|
|
185
|
+
### Endpoints
|
|
186
|
+
|
|
187
|
+
| Method | Path | Description |
|
|
188
|
+
|--------|------|-------------|
|
|
189
|
+
| GET | `/` | Self-contained HTML explorer page |
|
|
190
|
+
| GET | `/meta` | JSON config — `{ title, allow_execute }` |
|
|
191
|
+
| GET | `/tools` | Summary list of all tools |
|
|
192
|
+
| GET | `/tools/{name}` | Full tool detail with `inputSchema` |
|
|
193
|
+
| POST | `/tools/{name}/call` | Execute a tool, returns MCP `CallToolResult` |
|
|
194
|
+
|
|
195
|
+
## Development
|
|
196
|
+
|
|
197
|
+
```bash
|
|
198
|
+
# Install in editable mode with dev dependencies
|
|
199
|
+
pip install -e ".[dev]"
|
|
200
|
+
|
|
201
|
+
# Run the demo
|
|
202
|
+
python examples/fastapi_demo.py
|
|
203
|
+
# Visit http://localhost:8000/explorer/
|
|
204
|
+
|
|
205
|
+
# Run tests
|
|
206
|
+
pytest
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
## Cross-Language Specification
|
|
210
|
+
|
|
211
|
+
This package implements the [mcp-embedded-ui](https://github.com/aipartnerup/mcp-embedded-ui) specification. The spec repo contains:
|
|
212
|
+
|
|
213
|
+
- [PROTOCOL.md](https://github.com/aipartnerup/mcp-embedded-ui/blob/main/docs/PROTOCOL.md) — endpoint spec, data shapes, security checklist
|
|
214
|
+
- [explorer.html](https://github.com/aipartnerup/mcp-embedded-ui/blob/main/docs/explorer.html) — shared HTML template (identical across all language implementations)
|
|
215
|
+
- [Feature specs](https://github.com/aipartnerup/mcp-embedded-ui/blob/main/docs/features/MANIFEST.md) — detailed requirements and test criteria
|
|
216
|
+
|
|
217
|
+
## License
|
|
218
|
+
|
|
219
|
+
Apache-2.0
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
mcp_embedded_ui/__init__.py,sha256=P96vVUkfhUCV4EW_P9vKwV3wAAQMly6XYhBS2cFOqiQ,526
|
|
2
|
+
mcp_embedded_ui/html.py,sha256=KpJ89CkhRzXo-EJytSuRN4Z-TkwTFTwiGCOu3olof5A,16731
|
|
3
|
+
mcp_embedded_ui/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
mcp_embedded_ui/server.py,sha256=0iwXsvxcbI-GzzbMpDMA8BHhuGOyAMOGK-UGTJc9NaQ,9445
|
|
5
|
+
mcp_embedded_ui-0.1.0.dist-info/METADATA,sha256=ruzER4mBM1Xh1jtiQF1L83MSzKguFDIVAFLePryJBIk,8190
|
|
6
|
+
mcp_embedded_ui-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
7
|
+
mcp_embedded_ui-0.1.0.dist-info/RECORD,,
|