Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent): per-run tool allowlist + debug UI selectors, layout, condensed log

Akarshan Biswas88b6514745dc
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 3e1bd76c0..a37cf4d8e 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -89,6 +89,24 @@ pub(crate) async fn run_orchestration_streamed(
result
}
+/// Restrict the collected MCP tools to `allowed` (by tool name), pruning both
+/// the OpenAI tool array and the tool->server routing map in lockstep.
+fn apply_tool_allowlist(
+ openai_tools: &mut Vec<serde_json::Value>,
+ tool_to_server: &mut HashMap<String, String>,
+ allowed: &[String],
+) {
+ let allow: std::collections::HashSet<&str> = allowed.iter().map(String::as_str).collect();
+ openai_tools.retain(|t| {
+ t.get("function")
+ .and_then(|f| f.get("name"))
+ .and_then(|n| n.as_str())
+ .map(|n| allow.contains(n))
+ .unwrap_or(false)
+ });
+ tool_to_server.retain(|name, _| allow.contains(name.as_str()));
+}
+
fn stop_reason_of(completion: &serde_json::Value) -> String {
completion
.get("choices")
@@ -157,9 +175,19 @@ async fn orchestrate_inner(
}
let model_id = model_id.ok_or("No running model sessions available")?;
- let (openai_tools, tool_to_server) =
+ let (mut openai_tools, mut tool_to_server) =
collect_mcp_openai_tools(mcp_servers, mcp_settings).await?;
+ // Optional per-run allowlist: when `allowed_tools` is present, expose only
+ // those MCP tools (an empty array means no tools). Absent = all tools.
+ if let Some(allowed) = json_body.get("allowed_tools").and_then(|v| v.as_array()) {
+ let names: Vec<String> = allowed
+ .iter()
+ .filter_map(|v| v.as_str().map(String::from))
+ .collect();
+ apply_tool_allowlist(&mut openai_tools, &mut tool_to_server, &names);
+ }
+
let (upstream_url, session_api_keys) = resolve_upstream_for_model(
&model_id,
provider_configs.clone(),
@@ -292,4 +320,33 @@ mod tests {
assert_eq!(stop_reason_of(&json!({ "choices": [] })), "stop");
assert_eq!(stop_reason_of(&json!({})), "stop");
}
+
+ #[test]
+ fn tool_allowlist_keeps_only_named_tools() {
+ let mut tools = vec![
+ json!({ "type": "function", "function": { "name": "search" } }),
+ json!({ "type": "function", "function": { "name": "write" } }),
+ ];
+ let mut map = HashMap::from([
+ ("search".to_string(), "srv".to_string()),
+ ("write".to_string(), "srv".to_string()),
+ ]);
+
+ apply_tool_allowlist(&mut tools, &mut map, &["search".to_string()]);
+
+ assert_eq!(tools.len(), 1);
+ assert_eq!(tools[0]["function"]["name"], "search");
+ assert_eq!(map.keys().collect::<Vec<_>>(), vec!["search"]);
+ }
+
+ #[test]
+ fn tool_allowlist_empty_removes_all() {
+ let mut tools = vec![json!({ "type": "function", "function": { "name": "search" } })];
+ let mut map = HashMap::from([("search".to_string(), "srv".to_string())]);
+
+ apply_tool_allowlist(&mut tools, &mut map, &[]);
+
+ assert!(tools.is_empty());
+ assert!(map.is_empty());
+ }
}
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 98268c80d..a33f2547c 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -3,6 +3,8 @@
"title": "Agent Debug",
"modelLabel": "Model",
"modelAuto": "Auto (first running model)",
+ "toolsLabel": "Tools",
+ "noTools": "No MCP tools available.",
"promptLabel": "Prompt",
"promptPlaceholder": "Type a message for the agent loop...",
"run": "Run",
diff --git a/web-app/src/routes/agent-debug.tsx b/web-app/src/routes/agent-debug.tsx
index 4eef0c343..9d31f3110 100644
--- a/web-app/src/routes/agent-debug.tsx
+++ b/web-app/src/routes/agent-debug.tsx
@@ -1,32 +1,67 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { createFileRoute } from '@tanstack/react-router'
-import { useMemo, useRef, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
import { IconRobot } from '@tabler/icons-react'
import { route } from '@/constants/routes'
import { useServiceHub } from '@/hooks/useServiceHub'
import { useModelProvider } from '@/hooks/useModelProvider'
import { useTranslation } from '@/i18n/react-i18next-compat'
import type { StreamEvent } from '@/services/agent/types'
+import type { MCPTool } from '@/types/completion'
export const Route = createFileRoute(route.agentDebug as any)({
component: AgentDebugPanel,
})
-function describeEvent(event: StreamEvent): string {
- switch (event.type) {
- case 'token':
- return `token: ${JSON.stringify(event.text)}`
- case 'step':
- return `step ${event.index}/${event.max}`
- case 'tool_call':
- return `tool_call ${event.name} (${event.id}) ${JSON.stringify(event.args)}`
- case 'tool_result':
- return `tool_result ${event.id}${event.is_error ? ' [error]' : ''}: ${event.content}`
- case 'done':
- return `done: ${event.stop_reason}`
- case 'error':
- return `error [${event.code}]: ${event.message}`
+function truncate(text: string, max = 140): string {
+ const flat = text.replace(/\s+/g, ' ').trim()
+ return flat.length > max ? `${flat.slice(0, max)}...` : flat
+}
+
+/** Collapse the raw event stream into a compact log: runs of token events
+ * become a single live counter, tool calls/results show name + short output. */
+function condenseEvents(events: StreamEvent[]): string[] {
+ const rows: string[] = []
+ const toolNames = new Map<string, string>()
+ let tokenRun = 0
+
+ const flushTokens = () => {
+ if (tokenRun > 0) {
+ rows.push(`streaming... (${tokenRun} token${tokenRun === 1 ? '' : 's'})`)
+ tokenRun = 0
+ }
+ }
+
+ for (const event of events) {
+ if (event.type === 'token') {
+ tokenRun++
+ continue
+ }
+ flushTokens()
+ switch (event.type) {
+ case 'step':
+ rows.push(`step ${event.index}/${event.max}`)
+ break
+ case 'tool_call':
+ toolNames.set(event.id, event.name)
+ rows.push(`tool_call: ${event.name}`)
+ break
+ case 'tool_result': {
+ const name = toolNames.get(event.id) ?? event.id
+ const flag = event.is_error ? ' [error]' : ''
+ rows.push(`tool_result: ${name}${flag} - ${truncate(event.content)}`)
+ break
+ }
+ case 'done':
+ rows.push(`done: ${event.stop_reason}`)
+ break
+ case 'error':
+ rows.push(`error [${event.code}]: ${event.message}`)
+ break
+ }
}
+ flushTokens()
+ return rows
}
function AgentDebugPanel() {
@@ -38,8 +73,30 @@ function AgentDebugPanel() {
const [modelId, setModelId] = useState('')
const [events, setEvents] = useState<StreamEvent[]>([])
const [running, setRunning] = useState(false)
+ const [availableTools, setAvailableTools] = useState<MCPTool[]>([])
+ const [selectedTools, setSelectedTools] = useState<Set<string>>(new Set())
const runIdRef = useRef<string | null>(null)
+ useEffect(() => {
+ serviceHub
+ .mcp()
+ .getTools()
+ .then((tools) => {
+ setAvailableTools(tools)
+ setSelectedTools(new Set(tools.map((tool) => tool.name)))
+ })
+ .catch((error) => console.error('Failed to load MCP tools:', error))
+ }, [serviceHub])
+
+ const toggleTool = (name: string) => {
+ setSelectedTools((prev) => {
+ const next = new Set(prev)
+ if (next.has(name)) next.delete(name)
+ else next.add(name)
+ return next
+ })
+ }
+
const modelOptions = useMemo(
() =>
providers
@@ -59,6 +116,8 @@ function AgentDebugPanel() {
[events]
)
+ const logRows = useMemo(() => condenseEvents(events), [events])
+
const handleRun = async () => {
if (running || !prompt.trim()) return
const runId = crypto.randomUUID()
@@ -71,6 +130,9 @@ function AgentDebugPanel() {
{
messages: [{ role: 'user', content: prompt }],
...(modelId ? { model: modelId } : {}),
+ ...(availableTools.length > 0
+ ? { allowed_tools: Array.from(selectedTools) }
+ : {}),
},
(event) => setEvents((prev) => [...prev, event])
)
@@ -92,7 +154,7 @@ function AgentDebugPanel() {
}
return (
- <div className="flex flex-col h-full bg-background overflow-y-auto p-6 gap-4">
+ <div className="flex flex-col h-full min-w-0 bg-background overflow-y-auto overflow-x-hidden p-6 gap-4">
<div className="flex items-center gap-2">
<IconRobot className="text-muted-foreground/80 size-6" />
<h1 className="text-xl font-bold text-muted-foreground">
@@ -118,19 +180,49 @@ function AgentDebugPanel() {
))}
</select>
+ <span className="text-sm text-muted-foreground">
+ {t('common:agentDebug.toolsLabel')}
+ </span>
+ <div className="bg-secondary/50 rounded-lg p-3 max-h-40 overflow-y-auto shrink-0">
+ {availableTools.length === 0 ? (
+ <div className="text-muted-foreground text-sm">
+ {t('common:agentDebug.noTools')}
+ </div>
+ ) : (
+ <ul className="flex flex-col gap-1">
+ {availableTools.map((tool) => (
+ <li key={tool.name}>
+ <label className="flex items-center gap-2 text-sm cursor-pointer">
+ <input
+ type="checkbox"
+ checked={selectedTools.has(tool.name)}
+ onChange={() => toggleTool(tool.name)}
+ disabled={running}
+ />
+ <span className="text-foreground">{tool.name}</span>
+ <span className="text-muted-foreground text-xs">
+ {tool.server}
+ </span>
+ </label>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+
<label className="text-sm text-muted-foreground" htmlFor="agent-prompt">
{t('common:agentDebug.promptLabel')}
</label>
<textarea
id="agent-prompt"
- className="bg-secondary/50 rounded-lg p-3 text-sm font-mono min-h-24 w-full"
+ className="bg-secondary/50 rounded-lg p-3 text-sm font-mono min-h-24 w-full shrink-0"
placeholder={t('common:agentDebug.promptPlaceholder')}
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
disabled={running}
/>
- <div className="flex gap-2">
+ <div className="flex gap-2 shrink-0">
<button
className="bg-primary text-primary-foreground rounded-md px-4 py-2 text-sm disabled:opacity-50"
onClick={handleRun}
@@ -154,16 +246,16 @@ function AgentDebugPanel() {
</button>
</div>
- <div className="bg-secondary/50 rounded-lg p-3">
+ <div className="bg-secondary/50 rounded-lg p-3 min-w-0 shrink-0">
<h2 className="text-base font-semibold mb-2">
{t('common:agentDebug.output')}
</h2>
- <pre className="text-sm whitespace-pre-wrap break-words min-h-12 max-h-48 overflow-y-auto">
+ <pre className="text-sm whitespace-pre-wrap [overflow-wrap:anywhere] min-h-12 max-h-48 overflow-y-auto">
{streamedText}
</pre>
</div>
- <div className="bg-secondary/50 rounded-lg p-3">
+ <div className="bg-secondary/50 rounded-lg p-3 min-w-0 shrink-0">
<h2 className="text-base font-semibold mb-2">
{t('common:agentDebug.eventLog')}
</h2>
@@ -172,10 +264,13 @@ function AgentDebugPanel() {
{t('common:agentDebug.empty')}
</div>
) : (
- <ol className="text-xs font-mono flex flex-col gap-1 max-h-80 overflow-y-auto">
- {events.map((event, i) => (
- <li key={i} className="text-foreground break-words">
- {describeEvent(event)}
+ <ol className="text-xs font-mono flex flex-col gap-1 max-h-80 overflow-y-auto overflow-x-hidden">
+ {logRows.map((row, i) => (
+ <li
+ key={i}
+ className="text-foreground whitespace-pre-wrap [overflow-wrap:anywhere]"
+ >
+ {row}
</li>
))}
</ol>
diff --git a/web-app/src/services/agent/types.ts b/web-app/src/services/agent/types.ts
index 5ea5a3bf1..d62e61055 100644
--- a/web-app/src/services/agent/types.ts
+++ b/web-app/src/services/agent/types.ts
@@ -27,6 +27,9 @@ export interface AgentRunBody {
messages: AgentRunMessage[]
model?: string
max_turns?: number
+ /** Per-run MCP tool allowlist (by tool name). Omit for all tools; empty
+ * array for none. */
+ allowed_tools?: string[]
[key: string]: unknown
}