mirror of
https://github.com/open-webui/computer.git
synced 2026-11-26 15:21:01 -05:00
refac
This commit is contained in:
1 parent
32ee80d6f0
commit
aedafae389
12 files changed
+1349
-23
No files matched your search
@@ -128,3 +128,41 @@ export const updateModelConfig = (
|
||||
...jsonBody(update),
|
||||
method: 'PUT'
|
||||
});
|
||||
|
||||
// ── Tool Servers ────────────────────────────────────────────
|
||||
|
||||
export interface ToolServer {
|
||||
id: string;
|
||||
type: 'openapi' | 'mcp';
|
||||
url: string;
|
||||
path: string;
|
||||
auth_type: string;
|
||||
key: string;
|
||||
name: string;
|
||||
description: string;
|
||||
headers: Record<string, string> | null;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export const listToolServers = async (): Promise<ToolServer[]> => {
|
||||
const data = await fetchJSON<{ servers: ToolServer[] }>('/api/admin/tools/servers');
|
||||
return data.servers;
|
||||
};
|
||||
|
||||
export const createToolServer = (server: Omit<ToolServer, 'id'>) =>
|
||||
fetchJSON('/api/admin/tools/servers', jsonBody(server));
|
||||
|
||||
export const updateToolServer = (id: string, updates: Partial<Omit<ToolServer, 'id'>>) =>
|
||||
fetchJSON(`/api/admin/tools/servers/${id}`, {
|
||||
...jsonBody(updates),
|
||||
method: 'PUT'
|
||||
});
|
||||
|
||||
export const deleteToolServer = (id: string) =>
|
||||
fetchJSON(`/api/admin/tools/servers/${id}`, { method: 'DELETE' });
|
||||
|
||||
export const verifyToolServer = (id: string) =>
|
||||
fetchJSON<{ ok: boolean; tools?: { name: string; description: string }[]; message?: string }>(
|
||||
`/api/admin/tools/servers/${id}/verify`,
|
||||
{ method: 'POST' }
|
||||
);
|
||||
@@ -0,0 +1,444 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import Icon from '../Icon.svelte';
|
||||
import Modal from '../Modal.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import {
|
||||
listToolServers,
|
||||
createToolServer,
|
||||
updateToolServer,
|
||||
deleteToolServer,
|
||||
verifyToolServer,
|
||||
type ToolServer
|
||||
} from '$lib/apis/admin';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
let servers = $state<ToolServer[]>([]);
|
||||
let loading = $state(true);
|
||||
|
||||
// Modal state
|
||||
let showModal = $state(false);
|
||||
let editServer = $state<ToolServer | null>(null);
|
||||
|
||||
// Form state
|
||||
let formId = $state('');
|
||||
let formType = $state<'openapi' | 'mcp'>('openapi');
|
||||
let formUrl = $state('');
|
||||
let formPath = $state('openapi.json');
|
||||
let formAuthType = $state('bearer');
|
||||
let formKey = $state('');
|
||||
let formName = $state('');
|
||||
let formDescription = $state('');
|
||||
let formHeaders = $state('');
|
||||
|
||||
let saving = $state(false);
|
||||
let verifying = $state(false);
|
||||
|
||||
// Verify result
|
||||
let verifyResult = $state<{ ok: boolean; tools?: any[]; message?: string } | null>(null);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
servers = await listToolServers();
|
||||
} catch {
|
||||
toast.error($t('toolServers.loadError'));
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
editServer = null;
|
||||
formId = '';
|
||||
formType = 'openapi';
|
||||
formUrl = '';
|
||||
formPath = 'openapi.json';
|
||||
formAuthType = 'bearer';
|
||||
formKey = '';
|
||||
formName = '';
|
||||
formDescription = '';
|
||||
formHeaders = '';
|
||||
|
||||
verifyResult = null;
|
||||
showModal = true;
|
||||
}
|
||||
|
||||
function openEdit(s: ToolServer) {
|
||||
editServer = s;
|
||||
formId = s.id;
|
||||
formType = s.type;
|
||||
formUrl = s.url;
|
||||
formPath = s.path;
|
||||
formAuthType = s.auth_type;
|
||||
formKey = '';
|
||||
formName = s.name;
|
||||
formDescription = s.description;
|
||||
formHeaders = s.headers ? JSON.stringify(s.headers, null, 2) : '';
|
||||
|
||||
verifyResult = null;
|
||||
showModal = true;
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!formId.trim() || !formUrl.trim()) {
|
||||
toast.error($t('toolServers.fieldsRequired'));
|
||||
return;
|
||||
}
|
||||
if (/[^a-z0-9_]/.test(formId.trim())) {
|
||||
toast.error($t('toolServers.idInvalid'));
|
||||
return;
|
||||
}
|
||||
let parsedHeaders: Record<string, string> | undefined;
|
||||
if (formHeaders.trim()) {
|
||||
try {
|
||||
parsedHeaders = JSON.parse(formHeaders);
|
||||
if (typeof parsedHeaders !== 'object' || Array.isArray(parsedHeaders)) throw 0;
|
||||
} catch {
|
||||
toast.error($t('toolServers.headersInvalid'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
saving = true;
|
||||
try {
|
||||
const data: Record<string, unknown> = {
|
||||
id: formId.trim(),
|
||||
type: formType,
|
||||
url: formUrl.trim(),
|
||||
path: formPath,
|
||||
auth_type: formAuthType,
|
||||
name:
|
||||
formName.trim() ||
|
||||
(() => {
|
||||
try {
|
||||
return new URL(formUrl.trim()).hostname;
|
||||
} catch {
|
||||
return formType;
|
||||
}
|
||||
})(),
|
||||
description: formDescription.trim(),
|
||||
headers: parsedHeaders || null
|
||||
};
|
||||
if (editServer) {
|
||||
if (formKey.trim()) data.key = formKey.trim();
|
||||
await updateToolServer(editServer.id, data as any);
|
||||
toast.success($t('toolServers.updated'));
|
||||
} else {
|
||||
data.key = formKey.trim();
|
||||
await createToolServer(data as any);
|
||||
toast.success($t('toolServers.created'));
|
||||
}
|
||||
showModal = false;
|
||||
load();
|
||||
} catch {
|
||||
toast.error($t('toolServers.saveFailed'));
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete() {
|
||||
if (!editServer) return;
|
||||
try {
|
||||
await deleteToolServer(editServer.id);
|
||||
toast.success($t('toolServers.deleted'));
|
||||
showModal = false;
|
||||
load();
|
||||
} catch {
|
||||
toast.error($t('toolServers.deleteFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleVerify() {
|
||||
if (!editServer) return;
|
||||
verifying = true;
|
||||
verifyResult = null;
|
||||
try {
|
||||
verifyResult = await verifyToolServer(editServer.id);
|
||||
if (verifyResult.ok) toast.success($t('toolServers.connected'));
|
||||
else toast.error(verifyResult.message || 'Connection failed');
|
||||
} catch (e: any) {
|
||||
verifyResult = { ok: false, message: e?.message || 'Connection failed' };
|
||||
toast.error(verifyResult.message!);
|
||||
} finally {
|
||||
verifying = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleEnabled(e: Event, s: ToolServer) {
|
||||
e.stopPropagation();
|
||||
const newVal = !s.enabled;
|
||||
s.enabled = newVal;
|
||||
servers = [...servers];
|
||||
try {
|
||||
await updateToolServer(s.id, { enabled: newVal });
|
||||
} catch {
|
||||
s.enabled = !newVal;
|
||||
servers = [...servers];
|
||||
toast.error($t('toolServers.saveFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
onMount(load);
|
||||
</script>
|
||||
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white">{$t('toolServers.title')}</h2>
|
||||
<button
|
||||
class="flex items-center justify-center w-6 h-6 rounded-lg text-gray-400 hover:text-gray-700 dark:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
|
||||
onclick={() => openCreate()}
|
||||
>
|
||||
<Icon name="plus" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<div class="flex justify-center py-8">
|
||||
<Spinner size={16} />
|
||||
</div>
|
||||
{:else}
|
||||
<div>
|
||||
{#each servers as s}
|
||||
<button
|
||||
class="group flex items-center gap-2 w-full h-7 text-left"
|
||||
onclick={() => openEdit(s)}
|
||||
>
|
||||
<span
|
||||
class="text-[10px] font-mono shrink-0
|
||||
{s.type === 'mcp'
|
||||
? 'text-purple-500 dark:text-purple-400'
|
||||
: 'text-blue-500 dark:text-blue-400'}"
|
||||
>
|
||||
{s.type === 'mcp' ? 'MCP' : 'API'}
|
||||
</span>
|
||||
<span
|
||||
class="flex-1 text-[13px] truncate
|
||||
{s.enabled ? 'text-gray-700 dark:text-gray-300' : 'text-gray-400 dark:text-gray-600'}"
|
||||
>
|
||||
{s.name || s.url}
|
||||
</span>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="relative w-6 h-3.5 rounded-full shrink-0 cursor-pointer transition-colors duration-150
|
||||
{s.enabled ? 'bg-gray-900 dark:bg-white' : 'bg-gray-200 dark:bg-gray-700'}"
|
||||
role="switch"
|
||||
tabindex="-1"
|
||||
aria-checked={s.enabled}
|
||||
onclick={(e) => toggleEnabled(e, s)}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleEnabled(e, s);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span
|
||||
class="absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all duration-150
|
||||
{s.enabled ? 'left-3 bg-white dark:bg-gray-900' : 'left-0.5 bg-white dark:bg-gray-500'}"
|
||||
></span>
|
||||
</span>
|
||||
</button>
|
||||
{/each}
|
||||
|
||||
{#if servers.length === 0}
|
||||
<p class="text-[13px] text-gray-400 dark:text-gray-600 py-4">
|
||||
{$t('toolServers.empty')}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if showModal}
|
||||
<Modal onclose={() => (showModal = false)} class="w-full max-w-md mx-4">
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="p-4"
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' && formUrl.trim()) handleSubmit();
|
||||
}}
|
||||
>
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-3">
|
||||
{editServer ? $t('toolServers.edit') : $t('toolServers.add')}
|
||||
</h2>
|
||||
|
||||
<!-- ID + Type -->
|
||||
<div class="flex gap-3">
|
||||
<div class="flex-1">
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600"
|
||||
>{$t('toolServers.id')}</label
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="my_server"
|
||||
bind:value={formId}
|
||||
autofocus
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
disabled={!!editServer}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono disabled:opacity-50"
|
||||
/>
|
||||
</div>
|
||||
<div class="w-28 shrink-0">
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600"
|
||||
>{$t('toolServers.type')}</label
|
||||
>
|
||||
<select
|
||||
bind:value={formType}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer"
|
||||
>
|
||||
<option value="openapi">OpenAPI</option>
|
||||
<option value="mcp">MCP</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Name -->
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2"
|
||||
>{$t('toolServers.name')}</label
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Optional display name"
|
||||
bind:value={formName}
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5"
|
||||
/>
|
||||
|
||||
<!-- URL -->
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2"
|
||||
>{$t('toolServers.url')}</label
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
placeholder={formType === 'mcp'
|
||||
? 'https://mcp.example.com/mcp'
|
||||
: 'https://api.example.com'}
|
||||
bind:value={formUrl}
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
|
||||
/>
|
||||
|
||||
<!-- Spec path (OpenAPI only) -->
|
||||
{#if formType === 'openapi'}
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2"
|
||||
>{$t('toolServers.specPath')}</label
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="openapi.json"
|
||||
bind:value={formPath}
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<!-- Auth -->
|
||||
<div class="flex gap-3 mt-2">
|
||||
<div class="w-28 shrink-0">
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600"
|
||||
>{$t('toolServers.auth')}</label
|
||||
>
|
||||
<select
|
||||
bind:value={formAuthType}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer"
|
||||
>
|
||||
<option value="none">{$t('toolServers.authNone')}</option>
|
||||
<option value="bearer">{$t('toolServers.authBearer')}</option>
|
||||
</select>
|
||||
</div>
|
||||
{#if formAuthType === 'bearer'}
|
||||
<div class="flex-1">
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600"
|
||||
>{$t('toolServers.apiKey')}</label
|
||||
>
|
||||
<input
|
||||
type="password"
|
||||
placeholder={editServer ? '•••••••• (leave blank to keep)' : 'sk-...'}
|
||||
bind:value={formKey}
|
||||
autocomplete="new-password"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Description -->
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2"
|
||||
>{$t('toolServers.description')}</label
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
placeholder={$t('toolServers.descriptionPlaceholder')}
|
||||
bind:value={formDescription}
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5"
|
||||
/>
|
||||
|
||||
<!-- Headers -->
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2"
|
||||
>{$t('toolServers.headers')}</label
|
||||
>
|
||||
<p class="text-[10px] text-gray-300 dark:text-gray-700 mb-0.5">{$t('toolServers.headersHint')}</p>
|
||||
<textarea
|
||||
placeholder={'{"X-Custom-Header": "value"}'}
|
||||
bind:value={formHeaders}
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
rows="2"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono resize-none"
|
||||
></textarea>
|
||||
|
||||
|
||||
<!-- Verify result -->
|
||||
{#if verifyResult?.ok && verifyResult.tools}
|
||||
<div class="mt-2 text-[11px] text-gray-500 dark:text-gray-400">
|
||||
{verifyResult.tools.length}
|
||||
{$t('toolServers.toolsFound')}:
|
||||
<span class="text-gray-400 dark:text-gray-500"
|
||||
>{verifyResult.tools.map((t) => t.name).join(', ')}</span
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Actions -->
|
||||
<div class="flex items-center justify-between mt-3">
|
||||
<div class="flex items-center gap-3">
|
||||
{#if editServer}
|
||||
<button
|
||||
class="text-[13px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={handleDelete}>{$t('toolServers.delete')}</button
|
||||
>
|
||||
<button
|
||||
class="text-[13px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 disabled:opacity-30"
|
||||
disabled={verifying}
|
||||
onclick={handleVerify}
|
||||
>
|
||||
{#if verifying}
|
||||
<Spinner size={12} />
|
||||
{:else}
|
||||
{$t('toolServers.verify')}
|
||||
{/if}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
<button
|
||||
disabled={saving || !formUrl.trim()}
|
||||
onclick={handleSubmit}
|
||||
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 disabled:opacity-30 disabled:pointer-events-none"
|
||||
>
|
||||
{#if saving}
|
||||
<Spinner size={14} />
|
||||
{:else if editServer}
|
||||
{$t('settings.save')} →
|
||||
{:else}
|
||||
{$t('toolServers.add')} →
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
{/if}
|
||||
@@ -12,6 +12,7 @@
|
||||
import Gateway from './Admin/Gateway.svelte';
|
||||
import AudioSettings from './Admin/AudioSettings.svelte';
|
||||
import AdminWeb from './Admin/Web.svelte';
|
||||
import ToolServers from './Admin/ToolServers.svelte';
|
||||
import { session } from '$lib/session';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
@@ -26,7 +27,8 @@
|
||||
| 'messaging'
|
||||
| 'gateway'
|
||||
| 'audio'
|
||||
| 'web';
|
||||
| 'web'
|
||||
| 'toolservers';
|
||||
|
||||
interface Props {
|
||||
onclose: () => void;
|
||||
@@ -53,7 +55,8 @@
|
||||
{ id: 'messaging', label: $t('admin.messaging'), icon: 'chat-bubble' },
|
||||
{ id: 'gateway', label: $t('admin.gateway.tab'), icon: 'gateway' },
|
||||
{ id: 'audio', label: $t('admin.audio.title'), icon: 'microphone' },
|
||||
{ id: 'web', label: $t('admin.web'), icon: 'globe' }
|
||||
{ id: 'web', label: $t('admin.web'), icon: 'globe' },
|
||||
{ id: 'toolservers', label: $t('admin.toolServers'), icon: 'plug' }
|
||||
]);
|
||||
</script>
|
||||
|
||||
@@ -132,6 +135,8 @@
|
||||
<AudioSettings />
|
||||
{:else if activeTab === 'web'}
|
||||
<AdminWeb />
|
||||
{:else if activeTab === 'toolservers'}
|
||||
<ToolServers />
|
||||
{/if}
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -178,8 +178,16 @@
|
||||
return _t('chat.tool.fetchUrlFallback');
|
||||
}
|
||||
}
|
||||
default:
|
||||
default: {
|
||||
// External tool: {server_id}_{tool_name} → "tool_name (server_id)"
|
||||
const idx = name.indexOf('_');
|
||||
if (idx > 0) {
|
||||
const serverId = name.slice(0, idx);
|
||||
const toolName = name.slice(idx + 1);
|
||||
return `${toolName} (${serverId})`;
|
||||
}
|
||||
return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -645,6 +645,41 @@
|
||||
|
||||
"chat.dictate.unsupported": "Speech recognition not supported in this browser.",
|
||||
"chat.fallbackTitle": "Chat",
|
||||
"chat.greeting": "What can I help you with?"
|
||||
"chat.greeting": "What can I help you with?",
|
||||
|
||||
"admin.toolServers": "Tool Servers",
|
||||
|
||||
"toolServers.title": "Tool Servers",
|
||||
"toolServers.empty": "No tool servers configured",
|
||||
"toolServers.add": "Add Server",
|
||||
"toolServers.edit": "Edit Server",
|
||||
"toolServers.id": "ID",
|
||||
"toolServers.name": "Name",
|
||||
"toolServers.type": "Type",
|
||||
"toolServers.namePlaceholder": "My MCP Server",
|
||||
"toolServers.url": "URL",
|
||||
"toolServers.specPath": "Spec path",
|
||||
"toolServers.fieldsRequired": "ID and URL are required",
|
||||
"toolServers.idInvalid": "ID must be lowercase letters, numbers, and underscores only",
|
||||
"toolServers.auth": "Auth",
|
||||
"toolServers.authNone": "None",
|
||||
"toolServers.authBearer": "Bearer",
|
||||
"toolServers.apiKey": "API Key",
|
||||
"toolServers.description": "Description",
|
||||
"toolServers.descriptionPlaceholder": "What does this server do?",
|
||||
"toolServers.headers": "Headers",
|
||||
"toolServers.headersHint": "Additional HTTP headers as JSON.",
|
||||
"toolServers.headersInvalid": "Headers must be a valid JSON object",
|
||||
"toolServers.verify": "Verify",
|
||||
"toolServers.connected": "Connected",
|
||||
"toolServers.toolsFound": "tools found",
|
||||
"toolServers.delete": "Delete",
|
||||
"toolServers.loadError": "Failed to load tool servers",
|
||||
"toolServers.urlRequired": "URL is required",
|
||||
"toolServers.created": "Tool server added",
|
||||
"toolServers.updated": "Tool server updated",
|
||||
"toolServers.deleted": "Tool server deleted",
|
||||
"toolServers.saveFailed": "Failed to save tool server",
|
||||
"toolServers.deleteFailed": "Failed to delete tool server"
|
||||
}
|
||||
|
||||
@@ -425,3 +425,170 @@ async def update_model_config(
|
||||
await Config.upsert({CONFIG_KEY_CHAT_MODELS: all_config})
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ── Tool servers ─────────────────────────────────────────────
|
||||
|
||||
CONFIG_KEY_TOOL_SERVERS = "tool_servers"
|
||||
|
||||
|
||||
async def _get_tool_servers() -> list[dict]:
|
||||
"""Get all tool server configs from config store."""
|
||||
return await Config.get(CONFIG_KEY_TOOL_SERVERS) or []
|
||||
|
||||
|
||||
async def _save_tool_servers(servers: list[dict]):
|
||||
"""Save tool server configs and invalidate cache."""
|
||||
await Config.upsert({CONFIG_KEY_TOOL_SERVERS: servers})
|
||||
from cptr.utils.tools import invalidate_tool_server_cache
|
||||
|
||||
invalidate_tool_server_cache()
|
||||
|
||||
|
||||
def _mask_tool_server(server: dict) -> dict:
|
||||
"""Return server with masked API key for display."""
|
||||
masked = {**server}
|
||||
if masked.get("key"):
|
||||
key = masked["key"]
|
||||
masked["key"] = key[:4] + "****" + key[-4:] if len(key) > 8 else "****"
|
||||
return masked
|
||||
|
||||
|
||||
@router.get("/tools/servers")
|
||||
async def list_tool_servers(request: Request):
|
||||
"""List all configured tool servers (keys masked)."""
|
||||
require_admin(request)
|
||||
servers = await _get_tool_servers()
|
||||
return {"servers": [_mask_tool_server(s) for s in servers]}
|
||||
|
||||
|
||||
class CreateToolServerRequest(BaseModel):
|
||||
id: str
|
||||
type: str = "openapi" # "openapi" | "mcp"
|
||||
url: str
|
||||
path: str = "openapi.json" # OpenAPI spec path (OpenAPI only)
|
||||
auth_type: str = "bearer" # "bearer" | "none"
|
||||
key: Optional[str] = None
|
||||
name: str = ""
|
||||
description: str = ""
|
||||
headers: Optional[dict] = None
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
@router.post("/tools/servers")
|
||||
async def create_tool_server(body: CreateToolServerRequest, request: Request):
|
||||
"""Add a new external tool server."""
|
||||
require_admin(request)
|
||||
import re as _re
|
||||
|
||||
server_id = body.id.strip()
|
||||
if not server_id or not _re.fullmatch(r"[a-z0-9_]+", server_id):
|
||||
raise HTTPException(400, "ID must be lowercase alphanumeric with underscores only")
|
||||
|
||||
servers = await _get_tool_servers()
|
||||
if any(s["id"] == server_id for s in servers):
|
||||
raise HTTPException(409, f"Server ID '{server_id}' already exists")
|
||||
|
||||
server = {
|
||||
"id": server_id,
|
||||
"type": body.type,
|
||||
"url": body.url,
|
||||
"path": body.path,
|
||||
"auth_type": body.auth_type,
|
||||
"key": body.key or "",
|
||||
"name": body.name or server_id,
|
||||
"description": body.description,
|
||||
"headers": body.headers,
|
||||
"enabled": body.enabled,
|
||||
}
|
||||
servers.append(server)
|
||||
await _save_tool_servers(servers)
|
||||
return {"ok": True, "id": server["id"]}
|
||||
|
||||
|
||||
class UpdateToolServerRequest(BaseModel):
|
||||
type: Optional[str] = None
|
||||
url: Optional[str] = None
|
||||
path: Optional[str] = None
|
||||
auth_type: Optional[str] = None
|
||||
key: Optional[str] = None
|
||||
name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
headers: Optional[dict] = None
|
||||
enabled: Optional[bool] = None
|
||||
|
||||
|
||||
@router.put("/tools/servers/{server_id}")
|
||||
async def update_tool_server(server_id: str, body: UpdateToolServerRequest, request: Request):
|
||||
"""Update an existing tool server."""
|
||||
require_admin(request)
|
||||
servers = await _get_tool_servers()
|
||||
server = next((s for s in servers if s["id"] == server_id), None)
|
||||
if not server:
|
||||
raise HTTPException(404, "tool server not found")
|
||||
|
||||
for field in ("type", "url", "path", "auth_type", "name", "description"):
|
||||
val = getattr(body, field)
|
||||
if val is not None:
|
||||
server[field] = val
|
||||
if body.key is not None and body.key != "":
|
||||
server["key"] = body.key
|
||||
if body.headers is not None:
|
||||
server["headers"] = body.headers
|
||||
if body.enabled is not None:
|
||||
server["enabled"] = body.enabled
|
||||
|
||||
await _save_tool_servers(servers)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.delete("/tools/servers/{server_id}")
|
||||
async def delete_tool_server(server_id: str, request: Request):
|
||||
"""Delete a tool server."""
|
||||
require_admin(request)
|
||||
servers = [s for s in await _get_tool_servers() if s["id"] != server_id]
|
||||
await _save_tool_servers(servers)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/tools/servers/{server_id}/verify")
|
||||
async def verify_tool_server(server_id: str, request: Request):
|
||||
"""Test connectivity to a tool server. Returns discovered tools."""
|
||||
require_admin(request)
|
||||
servers = await _get_tool_servers()
|
||||
server = next((s for s in servers if s["id"] == server_id), None)
|
||||
if not server:
|
||||
raise HTTPException(404, "tool server not found")
|
||||
|
||||
server_type = server.get("type", "openapi")
|
||||
url = server.get("url", "")
|
||||
headers = dict(server.get("headers") or {})
|
||||
if server.get("auth_type") == "bearer" and server.get("key"):
|
||||
headers["Authorization"] = f"Bearer {server['key']}"
|
||||
|
||||
try:
|
||||
if server_type == "mcp":
|
||||
from cptr.utils.mcp.client import MCPClient
|
||||
|
||||
client = MCPClient()
|
||||
await client.connect(url, headers or None)
|
||||
try:
|
||||
specs = await client.list_tool_specs()
|
||||
return {"ok": True, "tools": specs}
|
||||
finally:
|
||||
await client.disconnect()
|
||||
|
||||
else: # openapi
|
||||
from cptr.utils.openapi import fetch_openapi_spec, convert_openapi_to_tool_specs
|
||||
|
||||
path = server.get("path", "openapi.json")
|
||||
if path.startswith("http"):
|
||||
spec_url = path
|
||||
else:
|
||||
spec_url = f"{url.rstrip('/')}/{path.lstrip('/')}"
|
||||
|
||||
spec = await fetch_openapi_spec(spec_url, headers or None)
|
||||
tools = convert_openapi_to_tool_specs(spec)
|
||||
return {"ok": True, "tools": tools}
|
||||
|
||||
except Exception as e:
|
||||
return JSONResponse({"ok": False, "message": str(e)}, 400)
|
||||
@@ -26,7 +26,7 @@ from cptr.utils.ai import (
|
||||
)
|
||||
from cptr.utils.config import _get_jwt_secret, now_ms
|
||||
from cptr.utils.crypto import decrypt_key
|
||||
from cptr.utils.tools import TOOLS, execute_tool, get_tool_list, _fn_to_schema, create_artifact
|
||||
from cptr.utils.tools import ALL_TOOLS, execute_tool, get_tool_list, _fn_to_schema, create_artifact
|
||||
from cptr.utils.chat_export import export_chat_to_file
|
||||
from cptr.utils.json_parser import extract_json
|
||||
|
||||
@@ -891,7 +891,7 @@ async def run_chat_task(
|
||||
# Plan mode: strip write tools, inject prompt as user message (not system, to preserve cache)
|
||||
plan_mode = chat_params.get("plan_mode", False)
|
||||
if plan_mode:
|
||||
tools = [t for t in tools if TOOLS.get(t["name"], {}).get("auto")]
|
||||
tools = [t for t in tools if ALL_TOOLS.get(t["name"], {}).get("auto")]
|
||||
# Inject create_artifact (only available in plan mode)
|
||||
tools.append(_fn_to_schema("create_artifact", create_artifact))
|
||||
messages.append({"role": "user", "content": PLAN_MODE_PROMPT})
|
||||
@@ -1037,7 +1037,7 @@ async def run_chat_task(
|
||||
flushed_item = _flush_text()
|
||||
|
||||
name = event["name"]
|
||||
tool = TOOLS.get(name)
|
||||
tool = ALL_TOOLS.get(name)
|
||||
item = {
|
||||
"type": "function_call",
|
||||
"id": str(uuid.uuid4()),
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
# MCP client utilities
|
||||
@@ -0,0 +1,147 @@
|
||||
"""MCP (Model Context Protocol) client for Streamable HTTP transport.
|
||||
|
||||
Wraps the `mcp` library's ClientSession to provide a simple interface
|
||||
for connecting to MCP servers, listing tools, and calling tools.
|
||||
|
||||
Usage::
|
||||
|
||||
client = MCPClient()
|
||||
await client.connect("https://mcp.example.com/sse", headers={"Authorization": "Bearer ..."})
|
||||
specs = await client.list_tool_specs()
|
||||
result = await client.call_tool("my_tool", {"arg": "value"})
|
||||
await client.disconnect()
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from contextlib import AsyncExitStack
|
||||
|
||||
import anyio
|
||||
from mcp import ClientSession
|
||||
from mcp.client.streamable_http import streamablehttp_client
|
||||
from mcp.types import CallToolResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_INIT_TIMEOUT = 30 # seconds
|
||||
|
||||
|
||||
class MCPClient:
|
||||
"""Manages a single MCP server connection over Streamable HTTP."""
|
||||
|
||||
def __init__(self):
|
||||
self.session: ClientSession | None = None
|
||||
self._exit_stack: AsyncExitStack | None = None
|
||||
|
||||
async def connect(self, url: str, headers: dict | None = None) -> None:
|
||||
"""Connect to an MCP server.
|
||||
|
||||
Args:
|
||||
url: The server's Streamable HTTP endpoint URL.
|
||||
headers: Optional HTTP headers (e.g. Authorization).
|
||||
"""
|
||||
async with AsyncExitStack() as exit_stack:
|
||||
try:
|
||||
transport = await exit_stack.enter_async_context(
|
||||
streamablehttp_client(url=url, headers=headers)
|
||||
)
|
||||
read, write, _ = transport
|
||||
|
||||
self.session = await exit_stack.enter_async_context(
|
||||
ClientSession(read_stream=read, write_stream=write)
|
||||
)
|
||||
|
||||
with anyio.fail_after(_INIT_TIMEOUT):
|
||||
await self.session.initialize()
|
||||
|
||||
# Transfer ownership — prevent exit_stack.__aexit__ from
|
||||
# tearing everything down when we leave this block.
|
||||
self._exit_stack = exit_stack.pop_all()
|
||||
logger.info("[mcp] Connected to %s", url)
|
||||
except Exception:
|
||||
await asyncio.shield(self.disconnect())
|
||||
raise
|
||||
|
||||
async def list_tool_specs(self) -> list[dict]:
|
||||
"""List tools from the connected server as OpenAI-compatible schemas.
|
||||
|
||||
Returns a list of dicts, each with: name, description, parameters.
|
||||
"""
|
||||
if not self.session:
|
||||
raise RuntimeError("MCPClient is not connected")
|
||||
|
||||
result = await self.session.list_tools()
|
||||
specs = []
|
||||
|
||||
for tool in result.tools:
|
||||
spec = {
|
||||
"name": tool.name,
|
||||
"description": tool.description or "",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"required": [],
|
||||
},
|
||||
}
|
||||
|
||||
if tool.inputSchema:
|
||||
schema = tool.inputSchema
|
||||
spec["parameters"]["properties"] = schema.get("properties", {})
|
||||
spec["parameters"]["required"] = schema.get("required", [])
|
||||
|
||||
specs.append(spec)
|
||||
|
||||
return specs
|
||||
|
||||
async def call_tool(self, name: str, function_args: dict | None = None) -> list:
|
||||
"""Call a tool on the connected server.
|
||||
|
||||
Args:
|
||||
name: The tool name.
|
||||
function_args: Arguments to pass to the tool.
|
||||
|
||||
Returns:
|
||||
A list of content items from the tool result.
|
||||
|
||||
Raises:
|
||||
RuntimeError: If the tool returns an error result.
|
||||
"""
|
||||
if not self.session:
|
||||
raise RuntimeError("MCPClient is not connected")
|
||||
|
||||
result: CallToolResult = await self.session.call_tool(
|
||||
name, arguments=function_args or {}
|
||||
)
|
||||
|
||||
content = [item.model_dump() for item in result.content]
|
||||
|
||||
if result.isError:
|
||||
raise RuntimeError(f"MCP tool error: {content}")
|
||||
|
||||
return content
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
"""Disconnect from the MCP server. Idempotent.
|
||||
|
||||
IMPORTANT: Do NOT use asyncio.shield() or anyio.CancelScope here.
|
||||
The MCP SDK requires its TaskGroup to be exited in the same task
|
||||
that created it. Simply call aclose() directly.
|
||||
"""
|
||||
exit_stack = self._exit_stack
|
||||
if exit_stack is None:
|
||||
return
|
||||
|
||||
# Prevent double-close from concurrent callers
|
||||
self._exit_stack = None
|
||||
self.session = None
|
||||
|
||||
try:
|
||||
await exit_stack.aclose()
|
||||
except TimeoutError:
|
||||
logger.warning("[mcp] disconnect timed out")
|
||||
except RuntimeError as exc:
|
||||
logger.debug("[mcp] disconnect suppressed RuntimeError: %s", exc)
|
||||
except Exception:
|
||||
logger.debug("[mcp] Error during disconnect", exc_info=True)
|
||||
@@ -0,0 +1,311 @@
|
||||
"""OpenAPI tool server client.
|
||||
|
||||
Handles fetching OpenAPI specs, converting them to LLM-compatible tool schemas,
|
||||
and executing tool calls against OpenAPI servers.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Valid HTTP methods per OpenAPI 3.x
|
||||
_HTTP_METHODS = {"get", "put", "post", "delete", "options", "head", "patch", "trace"}
|
||||
|
||||
_TIMEOUT = 15 # seconds
|
||||
|
||||
|
||||
# ── Spec fetching ───────────────────────────────────────────
|
||||
|
||||
|
||||
async def fetch_openapi_spec(
|
||||
url: str, headers: dict | None = None, timeout: float = _TIMEOUT
|
||||
) -> dict:
|
||||
"""Fetch and parse an OpenAPI spec from a URL.
|
||||
|
||||
Supports JSON and YAML (if PyYAML is installed). Falls back to YAML
|
||||
parsing for non-JSON content.
|
||||
|
||||
Args:
|
||||
url: Full URL to the OpenAPI spec endpoint.
|
||||
headers: Optional HTTP headers (e.g. Authorization).
|
||||
timeout: Request timeout in seconds.
|
||||
|
||||
Returns:
|
||||
The parsed OpenAPI spec as a dict.
|
||||
"""
|
||||
_headers = {"Accept": "application/json"}
|
||||
if headers:
|
||||
_headers.update(headers)
|
||||
|
||||
async with httpx.AsyncClient(timeout=timeout, verify=True) as client:
|
||||
resp = await client.get(url, headers=_headers)
|
||||
resp.raise_for_status()
|
||||
|
||||
text = resp.text
|
||||
if url.lower().endswith((".yaml", ".yml")):
|
||||
import yaml
|
||||
|
||||
return yaml.safe_load(text)
|
||||
|
||||
try:
|
||||
return json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
# Fallback to YAML for non-.yml URLs that aren't valid JSON
|
||||
import yaml
|
||||
|
||||
return yaml.safe_load(text)
|
||||
|
||||
|
||||
# ── Schema conversion ──────────────────────────────────────
|
||||
|
||||
|
||||
def _resolve_schema(
|
||||
schema: dict, components: dict, resolved: set | None = None
|
||||
) -> dict:
|
||||
"""Recursively resolve $ref references in a JSON schema."""
|
||||
if not schema:
|
||||
return {}
|
||||
|
||||
if resolved is None:
|
||||
resolved = set()
|
||||
|
||||
if "$ref" in schema:
|
||||
ref_path = schema["$ref"]
|
||||
schema_name = ref_path.split("/")[-1]
|
||||
|
||||
if schema_name in resolved:
|
||||
return {} # Avoid infinite recursion
|
||||
|
||||
resolved.add(schema_name)
|
||||
|
||||
ref_parts = ref_path.strip("#/").split("/")
|
||||
target = components
|
||||
for part in ref_parts[1:]: # Skip 'components'
|
||||
target = target.get(part, {})
|
||||
return _resolve_schema(target, components, resolved)
|
||||
|
||||
result = copy.deepcopy(schema)
|
||||
|
||||
if "properties" in result:
|
||||
for prop, prop_schema in result["properties"].items():
|
||||
result["properties"][prop] = _resolve_schema(prop_schema, components)
|
||||
|
||||
if "items" in result:
|
||||
result["items"] = _resolve_schema(result["items"], components)
|
||||
|
||||
for keyword in ("oneOf", "anyOf", "allOf"):
|
||||
if keyword in result and isinstance(result[keyword], list):
|
||||
result[keyword] = [
|
||||
_resolve_schema(inner, components, resolved) for inner in result[keyword]
|
||||
]
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def convert_openapi_to_tool_specs(openapi_spec: dict) -> list[dict]:
|
||||
"""Convert an OpenAPI specification into tool schemas for the LLM.
|
||||
|
||||
Each operation with an ``operationId`` becomes a tool. Parameters and
|
||||
request body properties are flattened into a single ``parameters`` object.
|
||||
|
||||
Args:
|
||||
openapi_spec: The parsed OpenAPI spec dict.
|
||||
|
||||
Returns:
|
||||
A list of tool spec dicts with name, description, and parameters.
|
||||
"""
|
||||
specs = []
|
||||
components = openapi_spec.get("components", {})
|
||||
|
||||
for path, methods in openapi_spec.get("paths", {}).items():
|
||||
if not isinstance(methods, dict):
|
||||
continue
|
||||
|
||||
path_params = methods.get("parameters", [])
|
||||
if not isinstance(path_params, list):
|
||||
path_params = []
|
||||
|
||||
for method, operation in methods.items():
|
||||
if method not in _HTTP_METHODS:
|
||||
continue
|
||||
if not isinstance(operation, dict):
|
||||
continue
|
||||
if not operation.get("operationId"):
|
||||
continue
|
||||
|
||||
tool = {
|
||||
"name": operation["operationId"],
|
||||
"description": operation.get(
|
||||
"description", operation.get("summary", "No description available.")
|
||||
),
|
||||
"parameters": {"type": "object", "properties": {}, "required": []},
|
||||
}
|
||||
|
||||
# Merge path-level and operation-level params
|
||||
op_params = operation.get("parameters", [])
|
||||
if not isinstance(op_params, list):
|
||||
op_params = []
|
||||
|
||||
merged = {}
|
||||
for param in path_params:
|
||||
if isinstance(param, dict) and param.get("name"):
|
||||
merged[(param["name"], param.get("in", ""))] = param
|
||||
for param in op_params:
|
||||
if isinstance(param, dict) and param.get("name"):
|
||||
merged[(param["name"], param.get("in", ""))] = param
|
||||
|
||||
for param in merged.values():
|
||||
pname = param.get("name")
|
||||
if not pname:
|
||||
continue
|
||||
pschema = param.get("schema", {})
|
||||
desc = pschema.get("description", "") or param.get("description", "")
|
||||
if pschema.get("enum") and isinstance(pschema["enum"], list):
|
||||
desc += f'. Possible values: {", ".join(str(v) for v in pschema["enum"])}'
|
||||
|
||||
prop = {
|
||||
"type": pschema.get("type") or "string",
|
||||
"description": desc,
|
||||
}
|
||||
if pschema.get("type") == "array" and "items" in pschema:
|
||||
prop["items"] = pschema["items"]
|
||||
|
||||
prop = {k: v for k, v in prop.items() if v is not None}
|
||||
tool["parameters"]["properties"][pname] = prop
|
||||
if param.get("required"):
|
||||
tool["parameters"]["required"].append(pname)
|
||||
|
||||
# Extract requestBody
|
||||
request_body = operation.get("requestBody")
|
||||
if request_body:
|
||||
content = request_body.get("content", {})
|
||||
json_schema = content.get("application/json", {}).get("schema")
|
||||
if json_schema:
|
||||
resolved = _resolve_schema(json_schema, components)
|
||||
if resolved.get("properties"):
|
||||
tool["parameters"]["properties"].update(resolved["properties"])
|
||||
if "required" in resolved:
|
||||
tool["parameters"]["required"] = list(
|
||||
set(tool["parameters"]["required"] + resolved["required"])
|
||||
)
|
||||
elif resolved.get("type") == "array":
|
||||
tool["parameters"] = resolved
|
||||
|
||||
specs.append(tool)
|
||||
|
||||
return specs
|
||||
|
||||
|
||||
# ── Tool execution ──────────────────────────────────────────
|
||||
|
||||
|
||||
async def execute_openapi_tool(
|
||||
server_url: str,
|
||||
openapi_spec: dict,
|
||||
tool_name: str,
|
||||
args: dict,
|
||||
headers: dict | None = None,
|
||||
timeout: float = 60,
|
||||
) -> str:
|
||||
"""Execute a tool call against an OpenAPI server.
|
||||
|
||||
Resolves the route by operationId, separates path/query/body params,
|
||||
and makes the appropriate HTTP request.
|
||||
|
||||
Args:
|
||||
server_url: Base URL of the OpenAPI server.
|
||||
openapi_spec: The full parsed OpenAPI spec.
|
||||
tool_name: The operationId to call.
|
||||
args: Arguments from the LLM tool call.
|
||||
headers: Optional HTTP headers.
|
||||
timeout: Request timeout in seconds.
|
||||
|
||||
Returns:
|
||||
The response body as a string (JSON-serialized if structured).
|
||||
"""
|
||||
paths = openapi_spec.get("paths", {})
|
||||
|
||||
# Find matching route
|
||||
route_path = None
|
||||
http_method = None
|
||||
operation = None
|
||||
|
||||
for rpath, methods in paths.items():
|
||||
if not isinstance(methods, dict):
|
||||
continue
|
||||
for method, op in methods.items():
|
||||
if method not in _HTTP_METHODS:
|
||||
continue
|
||||
if isinstance(op, dict) and op.get("operationId") == tool_name:
|
||||
route_path = rpath
|
||||
http_method = method
|
||||
operation = op
|
||||
break
|
||||
if route_path:
|
||||
break
|
||||
|
||||
if not route_path or not operation:
|
||||
return json.dumps({"error": f"Operation '{tool_name}' not found in OpenAPI spec"})
|
||||
|
||||
# Classify parameters
|
||||
path_params = {}
|
||||
query_params = {}
|
||||
body_params = dict(args)
|
||||
|
||||
all_params = (operation.get("parameters") or []) + (
|
||||
paths.get(route_path, {}).get("parameters") or []
|
||||
)
|
||||
|
||||
for param in all_params:
|
||||
pname = param.get("name", "")
|
||||
pin = param.get("in", "")
|
||||
if pname in body_params:
|
||||
if pin == "path":
|
||||
path_params[pname] = body_params.pop(pname)
|
||||
elif pin == "query":
|
||||
query_params[pname] = body_params.pop(pname)
|
||||
elif pin == "header":
|
||||
body_params.pop(pname) # skip header params for now
|
||||
|
||||
# Build URL with path params
|
||||
url = server_url.rstrip("/") + route_path
|
||||
for pname, pval in path_params.items():
|
||||
url = url.replace(f"{{{pname}}}", str(pval))
|
||||
|
||||
_headers = {"Content-Type": "application/json"}
|
||||
if headers:
|
||||
_headers.update(headers)
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=timeout, verify=True) as client:
|
||||
if http_method in ("get", "head", "options"):
|
||||
resp = await client.request(
|
||||
http_method.upper(), url, headers=_headers, params=query_params
|
||||
)
|
||||
else:
|
||||
resp = await client.request(
|
||||
http_method.upper(),
|
||||
url,
|
||||
headers=_headers,
|
||||
params=query_params,
|
||||
json=body_params if body_params else None,
|
||||
)
|
||||
|
||||
# Try to parse as JSON
|
||||
try:
|
||||
data = resp.json()
|
||||
return json.dumps(data, indent=2, ensure_ascii=False)
|
||||
except Exception:
|
||||
return resp.text
|
||||
|
||||
except httpx.TimeoutException:
|
||||
return json.dumps({"error": f"Request to {url} timed out after {timeout}s"})
|
||||
except Exception as e:
|
||||
return json.dumps({"error": str(e)})
|
||||
+185
-16
@@ -1198,7 +1198,7 @@ TOOLS: dict[str, dict] = {
|
||||
"delete_automation": {"fn": delete_automation, "auto": False},
|
||||
}
|
||||
|
||||
# Browser tools — registered conditionally based on browser.enabled config
|
||||
# Browser tools — conditionally included in schemas based on browser.enabled
|
||||
BROWSER_TOOLS: dict[str, dict] = {
|
||||
"browser_navigate": {"fn": browser_navigate, "auto": False},
|
||||
"browser_snapshot": {"fn": browser_snapshot, "auto": True},
|
||||
@@ -1208,6 +1208,157 @@ BROWSER_TOOLS: dict[str, dict] = {
|
||||
"browser_evaluate": {"fn": browser_evaluate, "auto": False},
|
||||
}
|
||||
|
||||
# Combined lookup for execution and approval (always available regardless of config)
|
||||
ALL_TOOLS: dict[str, dict] = {**TOOLS, **BROWSER_TOOLS}
|
||||
|
||||
|
||||
# ── External tool servers ───────────────────────────────────
|
||||
|
||||
_tool_server_cache: dict | None = None # {"servers": [...], "tools": {name: {server, spec}}}
|
||||
|
||||
|
||||
async def _load_tool_servers() -> dict:
|
||||
"""Load and cache external tool server config + specs.
|
||||
|
||||
Returns a dict with 'servers' (raw config list) and 'tools' mapping
|
||||
prefixed tool names to {server, spec, type}.
|
||||
"""
|
||||
global _tool_server_cache
|
||||
if _tool_server_cache is not None:
|
||||
return _tool_server_cache
|
||||
|
||||
from cptr.models import Config
|
||||
|
||||
servers = await Config.get("tool_servers") or []
|
||||
tools: dict[str, dict] = {}
|
||||
|
||||
for server in servers:
|
||||
if not server.get("enabled", True):
|
||||
continue
|
||||
|
||||
server_id = server.get("id", "")
|
||||
server_type = server.get("type", "openapi")
|
||||
|
||||
try:
|
||||
if server_type == "openapi":
|
||||
from cptr.utils.openapi import fetch_openapi_spec, convert_openapi_to_tool_specs
|
||||
|
||||
url = server.get("url", "").rstrip("/")
|
||||
path = server.get("path", "openapi.json")
|
||||
if path.startswith("http"):
|
||||
spec_url = path
|
||||
else:
|
||||
spec_url = f"{url}/{path.lstrip('/')}"
|
||||
|
||||
headers = _build_server_headers(server)
|
||||
openapi_spec = await fetch_openapi_spec(spec_url, headers)
|
||||
server["_openapi_spec"] = openapi_spec
|
||||
|
||||
for spec in convert_openapi_to_tool_specs(openapi_spec):
|
||||
prefixed = f"{server_id}_{spec['name']}"
|
||||
tools[prefixed] = {
|
||||
"server": server,
|
||||
"spec": {**spec, "name": prefixed},
|
||||
"original_name": spec["name"],
|
||||
"type": "openapi",
|
||||
}
|
||||
|
||||
elif server_type == "mcp":
|
||||
from cptr.utils.mcp.client import MCPClient
|
||||
|
||||
client = MCPClient()
|
||||
headers = _build_server_headers(server)
|
||||
await client.connect(server.get("url", ""), headers)
|
||||
|
||||
for spec in await client.list_tool_specs():
|
||||
prefixed = f"{server_id}_{spec['name']}"
|
||||
tools[prefixed] = {
|
||||
"server": server,
|
||||
"spec": {**spec, "name": prefixed},
|
||||
"original_name": spec["name"],
|
||||
"type": "mcp",
|
||||
}
|
||||
|
||||
await client.disconnect()
|
||||
|
||||
except Exception:
|
||||
import logging
|
||||
|
||||
logging.getLogger(__name__).warning(
|
||||
"Failed to load tool server '%s'", server_id, exc_info=True
|
||||
)
|
||||
|
||||
_tool_server_cache = {"servers": servers, "tools": tools}
|
||||
return _tool_server_cache
|
||||
|
||||
|
||||
def invalidate_tool_server_cache() -> None:
|
||||
"""Clear the external tool server cache, forcing a reload on next access."""
|
||||
global _tool_server_cache
|
||||
_tool_server_cache = None
|
||||
|
||||
|
||||
def _build_server_headers(server: dict) -> dict | None:
|
||||
"""Build auth + custom headers for a tool server connection."""
|
||||
headers = dict(server.get("headers") or {})
|
||||
auth_type = server.get("auth_type", "bearer")
|
||||
if auth_type == "bearer":
|
||||
key = server.get("key", "")
|
||||
if key:
|
||||
headers["Authorization"] = f"Bearer {key}"
|
||||
return headers or None
|
||||
|
||||
|
||||
async def _execute_external_tool(name: str, args: dict) -> str:
|
||||
"""Execute an external tool by its prefixed name ({server_id}_{tool_name})."""
|
||||
cache = await _load_tool_servers()
|
||||
tool_info = cache["tools"].get(name)
|
||||
if not tool_info:
|
||||
return f"Error: external tool '{name}' not found"
|
||||
|
||||
server = tool_info["server"]
|
||||
original_name = tool_info["original_name"]
|
||||
tool_type = tool_info["type"]
|
||||
headers = _build_server_headers(server)
|
||||
|
||||
try:
|
||||
if tool_type == "mcp":
|
||||
from cptr.utils.mcp.client import MCPClient
|
||||
|
||||
client = MCPClient()
|
||||
await client.connect(server.get("url", ""), headers)
|
||||
try:
|
||||
result = await client.call_tool(original_name, args)
|
||||
# MCP returns a list of content items; extract text
|
||||
texts = []
|
||||
for item in result:
|
||||
if isinstance(item, dict):
|
||||
if item.get("type") == "text":
|
||||
texts.append(item.get("text", ""))
|
||||
else:
|
||||
texts.append(json.dumps(item))
|
||||
return "\n".join(texts) if texts else "(no output)"
|
||||
finally:
|
||||
await client.disconnect()
|
||||
|
||||
elif tool_type == "openapi":
|
||||
from cptr.utils.openapi import execute_openapi_tool
|
||||
|
||||
openapi_spec = server.get("_openapi_spec", {})
|
||||
return await execute_openapi_tool(
|
||||
server_url=server.get("url", "").rstrip("/"),
|
||||
openapi_spec=openapi_spec,
|
||||
tool_name=original_name,
|
||||
args=args,
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
else:
|
||||
return f"Error: unknown tool server type: {tool_type}"
|
||||
|
||||
except Exception as e:
|
||||
return f"Error executing external tool '{name}': {e}"
|
||||
|
||||
|
||||
# ── Schema from function signature ──────────────────────────
|
||||
|
||||
@@ -1264,7 +1415,8 @@ def _fn_to_schema(name: str, fn) -> dict:
|
||||
async def get_tool_list() -> list[dict]:
|
||||
"""Return tool schemas for the LLM.
|
||||
|
||||
Automatically includes browser tools when browser.enabled is true in config.
|
||||
Automatically includes browser tools when browser.enabled is true,
|
||||
and external tool server tools when configured.
|
||||
"""
|
||||
tools = dict(TOOLS)
|
||||
try:
|
||||
@@ -1274,21 +1426,38 @@ async def get_tool_list() -> list[dict]:
|
||||
tools.update(BROWSER_TOOLS)
|
||||
except Exception:
|
||||
pass
|
||||
return [_fn_to_schema(name, t["fn"]) for name, t in tools.items()]
|
||||
|
||||
schemas = [_fn_to_schema(name, t["fn"]) for name, t in tools.items()]
|
||||
|
||||
# Add external tool server schemas
|
||||
try:
|
||||
cache = await _load_tool_servers()
|
||||
for tool_info in cache["tools"].values():
|
||||
schemas.append(tool_info["spec"])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return schemas
|
||||
|
||||
|
||||
async def execute_tool(name: str, args: dict, __context__: dict) -> str:
|
||||
"""Execute a tool by name, injecting execution context."""
|
||||
info = TOOLS.get(name) or BROWSER_TOOLS.get(name)
|
||||
if not info:
|
||||
return f"Error: unknown tool: {name}"
|
||||
fn = info["fn"]
|
||||
try:
|
||||
sig = inspect.signature(fn)
|
||||
if "__context__" in sig.parameters:
|
||||
return await fn(**args, __context__=__context__)
|
||||
else:
|
||||
# Legacy tools: inject workspace directly
|
||||
return await fn(**args, workspace=__context__["workspace"])
|
||||
except Exception as e:
|
||||
return f"Error executing {name}: {e}"
|
||||
info = ALL_TOOLS.get(name)
|
||||
if info:
|
||||
fn = info["fn"]
|
||||
try:
|
||||
sig = inspect.signature(fn)
|
||||
if "__context__" in sig.parameters:
|
||||
return await fn(**args, __context__=__context__)
|
||||
else:
|
||||
# Legacy tools: inject workspace directly
|
||||
return await fn(**args, workspace=__context__["workspace"])
|
||||
except Exception as e:
|
||||
return f"Error executing {name}: {e}"
|
||||
|
||||
# Check external tool servers
|
||||
cache = await _load_tool_servers()
|
||||
if name in cache["tools"]:
|
||||
return await _execute_external_tool(name, args)
|
||||
|
||||
return f"Error: unknown tool: {name}"
|
||||
@@ -24,6 +24,7 @@ dependencies = [
|
||||
|
||||
[project.optional-dependencies]
|
||||
pam = ["python-pam>=2.0"]
|
||||
mcp = ["mcp>=1.8"]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
|
||||
Reference in new issue
Block a user