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(ui): let users bound MCP tool output and derive it from the context window

thinhlpg38382902b31f
diff --git a/web-app/src/hooks/useMCPServers.ts b/web-app/src/hooks/useMCPServers.ts
index 95b3df2b3..09c66caad 100644
--- a/web-app/src/hooks/useMCPServers.ts
+++ b/web-app/src/hooks/useMCPServers.ts
@@ -33,6 +33,12 @@ export type MCPSettings = {
useLightweightRouterModel: boolean
routerModelProvider: string
routerModelId: string
+ /**
+ * Per-tool-result character cap applied before the result enters conversation
+ * history, so one oversized result cannot exhaust the model's context. `0`
+ * disables the cap.
+ */
+ maxToolOutputChars: number
}
export const DEFAULT_MCP_SETTINGS: MCPSettings = {
@@ -44,6 +50,7 @@ export const DEFAULT_MCP_SETTINGS: MCPSettings = {
useLightweightRouterModel: false,
routerModelProvider: '',
routerModelId: '',
+ maxToolOutputChars: 40000,
}
type MCPServerStoreState = {
diff --git a/web-app/src/lib/__tests__/context-manager.test.ts b/web-app/src/lib/__tests__/context-manager.test.ts
index 888b84a74..14f2ad42f 100644
--- a/web-app/src/lib/__tests__/context-manager.test.ts
+++ b/web-app/src/lib/__tests__/context-manager.test.ts
@@ -5,6 +5,7 @@ import {
estimateMessageTokens,
trimMessages,
compactMessages,
+ deriveToolOutputCap,
type ContextManagerConfig,
} from '../context-manager'
@@ -229,3 +230,33 @@ describe('compactMessages', () => {
expect(result.compactedSummary).toBeUndefined()
})
})
+
+describe('deriveToolOutputCap', () => {
+ it('scales the budget with the model context window', () => {
+ const small = deriveToolOutputCap(8_192)
+ const large = deriveToolOutputCap(1_000_000)
+
+ expect(small).toBeGreaterThan(0)
+ expect(large).toBeGreaterThan(small!)
+ })
+
+ it('leaves most of the window for the conversation itself', () => {
+ // A single tool result must not be allowed to fill the context it lives in.
+ const ctxTokens = 100_000
+ const cap = deriveToolOutputCap(ctxTokens)!
+
+ expect(estimateTokens('x'.repeat(cap))).toBeLessThan(ctxTokens / 2)
+ })
+
+ it('returns undefined when the context window is unknown', () => {
+ // Remote providers often report no window; the user's setting then governs
+ // alone rather than a fabricated budget taking over.
+ expect(deriveToolOutputCap(undefined)).toBeUndefined()
+ expect(deriveToolOutputCap(0)).toBeUndefined()
+ expect(deriveToolOutputCap(-1)).toBeUndefined()
+ })
+
+ it('returns a whole number of characters', () => {
+ expect(Number.isInteger(deriveToolOutputCap(8_191))).toBe(true)
+ })
+})
diff --git a/web-app/src/lib/context-manager.ts b/web-app/src/lib/context-manager.ts
index 259eb9a89..153c1ee1b 100644
--- a/web-app/src/lib/context-manager.ts
+++ b/web-app/src/lib/context-manager.ts
@@ -15,6 +15,32 @@ export function estimateTokens(text: string): number {
return Math.ceil(text.length / CHARS_PER_TOKEN)
}
+/**
+ * Share of the model's context window a single tool result may occupy.
+ *
+ * One result should never crowd out the conversation that gives it meaning, so
+ * this is deliberately a minority of the window: enough for a substantial page
+ * or file, far short of the whole budget.
+ */
+const TOOL_OUTPUT_FRACTION_OF_CONTEXT = 0.25
+
+/**
+ * Per-tool-result character budget derived from the active model's context
+ * window, so a bigger window earns a proportionally bigger allowance instead of
+ * being held to one hardcoded number.
+ *
+ * Returns `undefined` when the window is unknown - remote providers often don't
+ * report one - leaving the user's configured cap in sole charge.
+ */
+export function deriveToolOutputCap(
+ contextWindowTokens: number | undefined
+): number | undefined {
+ if (!contextWindowTokens || contextWindowTokens <= 0) return undefined
+ return Math.floor(
+ contextWindowTokens * CHARS_PER_TOKEN * TOOL_OUTPUT_FRACTION_OF_CONTEXT
+ )
+}
+
function messageToText(message: UIMessage): string {
const parts: string[] = []
for (const part of message.parts) {
diff --git a/web-app/src/locales/en/mcp-servers.json b/web-app/src/locales/en/mcp-servers.json
index b1fa37d23..547a7266a 100644
--- a/web-app/src/locales/en/mcp-servers.json
+++ b/web-app/src/locales/en/mcp-servers.json
@@ -59,6 +59,8 @@
"description": "Configure how Jan manages and retries MCP servers.",
"toolCallTimeout": "Tool call timeout (seconds)",
"toolCallTimeoutDesc": "Maximum time to wait for an MCP tool response before timing out.",
+ "maxToolOutputChars": "Max tool output characters",
+ "maxToolOutputCharsDesc": "Longest tool result kept in the conversation. Anything past this is trimmed and marked as truncated, so one large result cannot exhaust the model's context. Set to 0 to keep results whole.",
"smartToolRouting": "Smart MCP tool routing",
"smartToolRoutingDesc": "When enabled, Jan selects relevant MCP servers before loading tools. Disable to always load the full MCP tool list.",
"useLightweightRouterModel": "Use a dedicated model for routing",
diff --git a/web-app/src/routes/settings/__tests__/mcp-servers.error.test.tsx b/web-app/src/routes/settings/__tests__/mcp-servers.error.test.tsx
index d7c4c8b45..7477377ed 100644
--- a/web-app/src/routes/settings/__tests__/mcp-servers.error.test.tsx
+++ b/web-app/src/routes/settings/__tests__/mcp-servers.error.test.tsx
@@ -6,6 +6,7 @@ import { useAppState } from '@/hooks/useAppState'
const activateMCPServer = vi.fn()
const deactivateMCPServer = vi.fn()
const getConnectedServers = vi.fn().mockResolvedValue([])
+const updateSettings = vi.fn()
vi.mock('@/containers/SettingsMenu', () => ({
default: () => <div data-testid="settings-menu">Settings Menu</div>,
@@ -121,6 +122,7 @@ vi.mock('@/hooks/useMCPServers', () => ({
useLightweightRouterModel: false,
routerModelProvider: '',
routerModelId: '',
+ maxToolOutputChars: 40000,
},
useMCPServers: () => ({
mcpServers: {
@@ -138,6 +140,7 @@ vi.mock('@/hooks/useMCPServers', () => ({
useLightweightRouterModel: false,
routerModelProvider: '',
routerModelId: '',
+ maxToolOutputChars: 40000,
},
addServer: vi.fn(),
editServer: vi.fn(),
@@ -153,7 +156,7 @@ vi.mock('@/hooks/useMCPServers', () => ({
active: false,
}),
setSettings: vi.fn(),
- updateSettings: vi.fn(),
+ updateSettings,
}),
}))
@@ -237,3 +240,52 @@ describe('MCP servers route error handling', () => {
})
})
})
+
+// #8557: users had no way to bound an MCP result before it filled the context.
+describe('max tool output characters control', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ getConnectedServers.mockResolvedValue([])
+ })
+
+ const capInput = (): HTMLInputElement => {
+ const inputs = screen.getAllByRole<HTMLInputElement>('spinbutton')
+ const found = inputs.find((i) => i.value === '40000')
+ if (!found) throw new Error('cap input not rendered')
+ return found
+ }
+
+ it('shows the configured cap and saves an edited one', async () => {
+ const Component = McpServersRoute.component as React.ComponentType
+ await act(async () => {
+ render(<Component />)
+ })
+
+ fireEvent.change(capInput(), { target: { value: '12000' } })
+
+ expect(updateSettings).toHaveBeenCalledWith({ maxToolOutputChars: 12000 })
+ })
+
+ it('accepts 0 as an explicit opt-out rather than rejecting it', async () => {
+ const Component = McpServersRoute.component as React.ComponentType
+ await act(async () => {
+ render(<Component />)
+ })
+
+ fireEvent.change(capInput(), { target: { value: '0' } })
+
+ expect(updateSettings).toHaveBeenCalledWith({ maxToolOutputChars: 0 })
+ })
+
+ it('restores the default when the field is cleared', async () => {
+ // An empty box must not persist as "0 characters of tool output".
+ const Component = McpServersRoute.component as React.ComponentType
+ await act(async () => {
+ render(<Component />)
+ })
+
+ fireEvent.change(capInput(), { target: { value: '' } })
+
+ expect(updateSettings).toHaveBeenCalledWith({ maxToolOutputChars: 40000 })
+ })
+})
diff --git a/web-app/src/routes/settings/mcp-servers.tsx b/web-app/src/routes/settings/mcp-servers.tsx
index 76f61db50..4f8affccc 100644
--- a/web-app/src/routes/settings/mcp-servers.tsx
+++ b/web-app/src/routes/settings/mcp-servers.tsx
@@ -174,6 +174,20 @@ function MCPServersDesktop() {
}
}
+ const updateMaxToolOutputChars = (rawValue: string) => {
+ if (rawValue === '') {
+ updateSettings({
+ maxToolOutputChars: DEFAULT_MCP_SETTINGS.maxToolOutputChars,
+ })
+ return
+ }
+
+ const numericValue = Number(rawValue)
+ if (!Number.isNaN(numericValue) && numericValue >= 0) {
+ updateSettings({ maxToolOutputChars: numericValue })
+ }
+ }
+
const modelProviders = useModelProvider((state) => state.providers)
const routerPickerDisabled =
@@ -577,6 +591,27 @@ function MCPServersDesktop() {
/>
}
/>
+ <CardItem
+ title={t('mcp-servers:runtimeSettings.maxToolOutputChars')}
+ description={t(
+ 'mcp-servers:runtimeSettings.maxToolOutputCharsDesc'
+ )}
+ actions={
+ <Input
+ type="number"
+ min={0}
+ step={1000}
+ value={settings.maxToolOutputChars}
+ onChange={(event) =>
+ updateMaxToolOutputChars(event.target.value)
+ }
+ onBlur={() => {
+ void syncServers()
+ }}
+ className="w-28"
+ />
+ }
+ />
<CardItem
title={t('mcp-servers:runtimeSettings.smartToolRouting')}
description={t(
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 124cce54f..68b06b18f 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -18,6 +18,7 @@ import { SESSION_STORAGE_PREFIX } from '@/constants/chat'
import { useChat } from '@/hooks/use-chat'
import { useModelProvider } from '@/hooks/useModelProvider'
import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'
+import { deriveToolOutputCap } from '@/lib/context-manager'
import { renderInstructions } from '@/lib/instructionTemplate'
import {
Conversation,
@@ -556,9 +557,18 @@ function ThreadDetail() {
scope: projectId ? 'project' : 'thread',
})
} else if (mcpToolNames.has(toolName)) {
+ // An MCP result is injected into conversation history verbatim, so
+ // a page-sized one can exhaust the context on its own. Give the
+ // backend a budget scaled to the window this model actually has;
+ // it narrows that against the user's configured ceiling.
+ const ctxLen = useModelProvider.getState().selectedModel?.settings
+ ?.ctx_len?.controller_props?.value
result = await serviceHub.mcp().callTool({
toolName,
arguments: toolCall.input,
+ maxOutputChars: deriveToolOutputCap(
+ typeof ctxLen === 'number' ? ctxLen : undefined
+ ),
})
} else {
result = {
diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
index c64b64525..a7a98271c 100644
--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx
+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
@@ -815,6 +815,60 @@ describe('ThreadDetail route', () => {
expect(h.toolApprovalState.requestApproval).toHaveBeenCalledTimes(1)
})
+ // A tool result is injected into conversation history verbatim, so an
+ // uncapped one can exhaust the context on its own (#8557). The budget the
+ // model's own window affords is handed to the backend, which enforces it.
+ it('caps the tool result against the active model context window', async () => {
+ h.appStateState.mcpToolNames = new Set(['fetch'])
+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)
+ const callTool = vi.fn().mockResolvedValue({ error: '', content: [] })
+ hub.mcp = () => ({ callTool }) as never
+ renderComponent()
+
+ const onToolCall = (
+ h as { capturedOnToolCall: (arg: unknown) => Promise<void> }
+ ).capturedOnToolCall
+ await act(async () => {
+ await onToolCall(toolCall('tc5'))
+ })
+ await act(async () => {
+ await finishWithToolCalls()
+ })
+
+ const { maxOutputChars } = callTool.mock.calls[0][0]
+ // 4096-token window in the harness: a fraction of it, not the whole thing.
+ expect(maxOutputChars).toBeGreaterThan(0)
+ expect(maxOutputChars).toBeLessThan(4096 * 3.5)
+ })
+
+ it('omits the cap when the model reports no context window', async () => {
+ // Remote providers often don't; the user's configured ceiling then governs
+ // alone rather than an invented budget silently clipping output.
+ h.appStateState.mcpToolNames = new Set(['fetch'])
+ h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(true)
+ const previousSettings = h.modelProviderState.selectedModel.settings
+ h.modelProviderState.selectedModel.settings = {}
+ const callTool = vi.fn().mockResolvedValue({ error: '', content: [] })
+ hub.mcp = () => ({ callTool }) as never
+
+ try {
+ renderComponent()
+ const onToolCall = (
+ h as { capturedOnToolCall: (arg: unknown) => Promise<void> }
+ ).capturedOnToolCall
+ await act(async () => {
+ await onToolCall(toolCall('tc6'))
+ })
+ await act(async () => {
+ await finishWithToolCalls()
+ })
+
+ expect(callTool.mock.calls[0][0].maxOutputChars).toBeUndefined()
+ } finally {
+ h.modelProviderState.selectedModel.settings = previousSettings
+ }
+ })
+
// A model can request several tools in one turn. They arrive together but
// are executed one at a time, which is what the queue display depends on.
describe('several tool calls in one turn', () => {
diff --git a/web-app/src/services/mcp/default.ts b/web-app/src/services/mcp/default.ts
index 8a053e0e0..0411f2892 100644
--- a/web-app/src/services/mcp/default.ts
+++ b/web-app/src/services/mcp/default.ts
@@ -43,7 +43,11 @@ export class DefaultMCPService implements MCPService {
return []
}
- async callTool(args: { toolName: string; arguments: object }): Promise<MCPToolCallResult> {
+ async callTool(args: {
+ toolName: string
+ arguments: object
+ maxOutputChars?: number
+ }): Promise<MCPToolCallResult> {
console.log('callTool called with args:', args)
return {
error: '',
diff --git a/web-app/src/services/mcp/tauri.ts b/web-app/src/services/mcp/tauri.ts
index eae859134..640115fe4 100644
--- a/web-app/src/services/mcp/tauri.ts
+++ b/web-app/src/services/mcp/tauri.ts
@@ -83,6 +83,7 @@ export class TauriMCPService extends DefaultMCPService {
toolName: string
serverName?: string
arguments: object
+ maxOutputChars?: number
}): Promise<{ error: string; content: { text: string }[] }> {
return window.core?.api?.callTool(args)
}
diff --git a/web-app/src/services/mcp/types.ts b/web-app/src/services/mcp/types.ts
index 11bfe2541..8945540f6 100644
--- a/web-app/src/services/mcp/types.ts
+++ b/web-app/src/services/mcp/types.ts
@@ -60,7 +60,17 @@ export interface MCPService {
/** Return name/capabilities/description for all connected servers. */
getServerSummaries(): Promise<ServerSummary[]>
getConnectedServers(): Promise<string[]>
- callTool(args: { toolName: string; serverName?: string; arguments: object }): Promise<MCPToolCallResult>
+ /**
+ * `maxOutputChars` is a per-result character budget derived from the active
+ * model's context window; the backend narrows its own configured cap to it so
+ * one oversized result cannot exhaust the context.
+ */
+ callTool(args: {
+ toolName: string
+ serverName?: string
+ arguments: object
+ maxOutputChars?: number
+ }): Promise<MCPToolCallResult>
callToolWithCancellation(args: {
toolName: string
serverName?: string