Skip to content

Commit dcc5297

Browse files
mhcp0001claude
andcommitted
fix(opencode): wait for the MCP tools in an OpenCode plugin instead of a read warm-up
The first model step of `opencode run --standalone` is built before the MCP server's tools are registered (anomalyco/opencode#51812, still open in 2.0.32). OpenCode has no setting for this, so opencode/plugins/wait-for-mcp holds each prompt in the prompt-admission hook until dexter_* tools are in the tool registry (up to 15 s). On CT105 with opencode-go/glm-5.3-flash the 3-company comparison then answered 10 of 10 times with the tools visible on the first step, no tool errors, no retries, and all six revenue / operating income figures right (the hook held each prompt about 0.9 s). - Drop opencode/dexter-tools.md and the read-first instruction; the tool list is back in the system prompt. - Tell the agent to report an EDINET DB 429 (100 requests/day on the free plan) instead of filling figures in from web search, which it did once. - The empty-answer retry stays as a backstop. Refs mhcp0001/homelab-infrastructure#650 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PC2eioeSBTUWiXjR22k4QK
1 parent 17e8b76 commit dcc5297

5 files changed

Lines changed: 58 additions & 29 deletions

File tree

‎env.example‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,9 @@ JQUANTS_API_KEY=your-jquants-api-key
2727
# native (default): Dexter's own agent loop with the model in .dexter/settings.json
2828
# opencode: run each turn as `opencode run --agent dexter`; OpenCode calls the model and
2929
# reaches the finance tools through the MCP server (bun src/mcp/server.ts).
30-
# System prompt for the agent: opencode/dexter-system.md. Copy opencode/dexter-tools.md
31-
# into DEXTER_OPENCODE_DIR: the agent reads it as its first step of every turn.
30+
# System prompt for the agent: opencode/dexter-system.md. Load the plugin
31+
# opencode/plugins/wait-for-mcp ("plugins" in opencode.json) so the first model step
32+
# sees the MCP tools.
3233
DEXTER_BACKEND=native
3334
# DEXTER_OPENCODE_BIN=/path/to/opencode
3435
# DEXTER_OPENCODE_DIR=/path/to/dir/with/opencode.json

‎opencode/dexter-system.md‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,33 @@
11
You are Dexter, an assistant specialized in Japanese stock market research, with access to research tools. Your answers are delivered through a chat app (Discord) or a command line.
22

3-
## Start of every turn
3+
## Available Tools
44

5-
Your first action in every turn is to call the read tool with the path `dexter-tools.md`, exactly as written (a file in the working directory). It lists the dexter_* tools and their arguments, and they become available after that first step. Then call the dexter_* tools you need.
5+
The `dexter_*` tools come from Dexter's MCP server and read EDINET DB (annual securities reports, TDNet disclosures) and J-Quants (TSE prices).
6+
7+
- dexter_resolve_company: find a company's EDINET code and securities code from a name or code. Use it when a name is ambiguous or another tool says the company was not found.
8+
- dexter_get_financial_statements: multi-year financial time series (revenue, operating income, net income, assets, equity, cash flows, EPS, dividends, and more). Use `years` to keep the window small.
9+
- dexter_get_company_info / dexter_get_key_ratios: latest-year snapshot and key ratios (ROE, margins, PER, equity ratio).
10+
- dexter_get_analysis: financial health score and AI-generated summary from EDINET DB.
11+
- dexter_get_earnings: recent TDNet earnings disclosures (決算短信), only about the last 30 days.
12+
- dexter_get_text_blocks: text of the annual securities report (事業の状況, 事業等のリスク, 経営者による分析, 経営方針).
13+
- dexter_get_shareholders: large shareholding reports (大量保有報告書).
14+
- dexter_screen_companies: screen companies by financial metrics with structured conditions.
15+
- dexter_get_stock_price (when present): daily prices from J-Quants.
16+
- dexter_web_search (when present) and webfetch: news and facts outside the structured data. Use webfetch only for a URL you already have.
17+
18+
Arguments: company tools take `ticker` (e.g. {"ticker": "7203"}); dexter_resolve_company takes `query`.
19+
Large amounts come with a sibling field ending in `_jp` (revenue_jp: "50兆6,850億円").
620

721
## Tool Usage Policy
822

923
- Use the tools for every company-specific figure. Never state a financial number from memory.
10-
- After reading dexter-tools.md, call the dexter_* tools. Do not write a plan instead of calling. If a call returns "No tool named ... is currently available", make the same call again in your next step.
24+
- For a company question, call the dexter_* tools. Do not write a plan instead of calling.
1125
- Securities codes (e.g. 7203) are the most reliable identifier. If a name is not found, try the 4-digit code or the English name, or use dexter_resolve_company.
1226
- To compare several companies, call the same tool once per company, then compute derived figures yourself (e.g. operating margin = operating income / revenue) and show the inputs you used.
1327
- Use the smallest data window that answers the question (years: 1-2 for "latest").
1428
- EDINET DB amounts are in yen, not millions (revenue 50684952000000 = about 50.7 trillion yen). Large amounts also come as a field ending in `_jp` (revenue_jp: "50兆6,850億円"): quote those in answers instead of converting yen yourself. State the fiscal year of every figure (`fiscal_year`).
1529
- If a tool fails or the data is missing, say so plainly and answer with what you have. Do not invent numbers.
30+
- If EDINET DB answers 429 (its daily request limit, which resets at midnight JST), say so. Do not fill in financial figures from web search instead.
1631
- Only respond without tools for conceptual definitions, stable historical facts, or conversation.
1732

1833
## Behavior

‎opencode/dexter-tools.md‎

Lines changed: 0 additions & 21 deletions
This file was deleted.
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* OpenCode plugin: hold each prompt until Dexter's MCP tools are in OpenCode's tool registry.
3+
*
4+
* `opencode run --standalone` starts the MCP server together with the session and builds the
5+
* first model request before the server's tools are registered (anomalyco/opencode#51812, still
6+
* open in 2.0.32). The first step then sees no dexter_* tools, and the model guesses or stops.
7+
* Waiting in the prompt-admission hook makes every turn start with the tools in place. After
8+
* LIMIT_MS it gives up and lets the turn run with whatever is registered.
9+
*
10+
* Loaded through "plugins" in opencode.json(c); OpenCode runs it, not Dexter.
11+
*/
12+
13+
type PluginContext = {
14+
session: { hook(name: 'prompt', handler: () => Promise<void>): Promise<unknown> };
15+
tool: { list(): Promise<ReadonlyArray<{ id: string }>> };
16+
};
17+
18+
const TOOL_PREFIX = 'dexter_';
19+
const LIMIT_MS = 15_000;
20+
const POLL_MS = 100;
21+
22+
export default {
23+
id: 'dexter-wait-for-mcp',
24+
async setup(ctx: PluginContext) {
25+
await ctx.session.hook('prompt', async () => {
26+
const started = Date.now();
27+
while (Date.now() - started < LIMIT_MS) {
28+
const tools = await ctx.tool.list();
29+
if (tools.some((tool) => tool.id.startsWith(TOOL_PREFIX))) return;
30+
await new Promise((resolve) => setTimeout(resolve, POLL_MS));
31+
}
32+
console.warn(`[dexter-wait-for-mcp] no ${TOOL_PREFIX}* tools after ${LIMIT_MS} ms; continuing without them`);
33+
});
34+
},
35+
};

‎src/gateway/opencode-runner.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -233,9 +233,8 @@ export async function runOpencodeForMessage(req: OpencodeRunRequest): Promise<st
233233

234234
/**
235235
* True when a run ended without a usable answer: no text, or only a plan that names our tools
236-
* without having called any. The MCP tools connect a moment after `opencode run` starts, so the
237-
* first model step can see no tools; the model then sometimes writes its plan and stops
238-
* (2 of 3 comparison questions in the #650 spike).
236+
* without having called any. The model did this when the first step could not see the MCP tools
237+
* (#650 spike); the wait-for-mcp plugin fixes the cause, and this retry stays as a backstop.
239238
*/
240239
export function needsRetry(result: Pick<OpencodeRunResult, 'answer' | 'tools'>): boolean {
241240
return !result.answer || (result.tools.length === 0 && /\bdexter_[a-z_]+/.test(result.answer));

0 commit comments

Comments
 (0)