Skip to content

armgit / Wake

Public Imported from GitHub
0

All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.

Rust

feat: let agents use Wake only when asked (#64)

Corey Chiu7cbb573f2c52
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6b526e3..2dd4987 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@
- Update: Subagent sessions from OpenCode, Kilo Code, ZCode, Antigravity and OpenClaw are listed under the session that started them. ZCode side chats and workflow steps sit under their task too, and ZCode workflow tasks are listed
- Fix: ZCode forks no longer repeat the task they were forked from, and their tokens are their own; side chats are titled with their first question instead of "Selection side chat"
- Update: Insights no longer counts subagent sessions, or the prompts in them, as yours; their tokens still count
+- New: You can have agents use Wake only when you ask, not on their own; "Only when you ask" in the MCP guide shows how (#64, thanks @ItsRyanWu)
## [0.9.1] — 2026-10-10
diff --git a/crates/wake-core/src/bin/wake_cli.rs b/crates/wake-core/src/bin/wake_cli.rs
index 89bba85..f5311d9 100644
--- a/crates/wake-core/src/bin/wake_cli.rs
+++ b/crates/wake-core/src/bin/wake_cli.rs
@@ -25,7 +25,7 @@ use std::process::ExitCode;
use wake_core::cli::{self, Action, CliError, Report, Stream};
use wake_core::db::{self, LockHolder, Store};
-use wake_core::mcp::{self, tools};
+use wake_core::mcp::{self, tools, Usage};
use wake_core::scanner::{self, NullEvents, Outcome, ScanEvents, ScanProgress, Skip};
fn main() -> ExitCode {
@@ -93,6 +93,18 @@ fn run(db: &Option<PathBuf>, tool: &str, args: &serde_json::Value) -> ExitCode {
/// 不写、退 0——钩子的输出原样进 agent 的上下文,连空行都是噪音。缺库、读不出照常走诊断
/// 出口,钩子那头自己吞掉
fn context(db: &Option<PathBuf>) -> ExitCode {
+ // 只在被要求时使用(#64):新会话开场什么都不加,与 wake-mcp 同一个开关、同一个判法。钩子把
+ // stderr 丢掉,这句只有在终端里自己跑的人看得见
+ if Usage::from_env() == Usage::OnRequest {
+ return write(Report {
+ stream: Stream::Stderr,
+ text: format!(
+ "wake-cli: {} is on, so new sessions get no context until you ask",
+ mcp::ON_REQUEST_ENV
+ ),
+ code: 0,
+ });
+ }
let dir = match std::env::current_dir() {
Ok(dir) => dir,
Err(e) => return write(refuse(format!("cannot read the current directory: {e}"))),
diff --git a/crates/wake-core/src/bin/wake_mcp.rs b/crates/wake-core/src/bin/wake_mcp.rs
index e546ae2..3c873d9 100644
--- a/crates/wake-core/src/bin/wake_mcp.rs
+++ b/crates/wake-core/src/bin/wake_mcp.rs
@@ -1,6 +1,7 @@
//! wake-mcp:Wake 索引的只读 MCP server(stdio)。
//!
-//! wake-mcp [--db PATH] 以 MCP server 身份服务 stdin/stdout(客户端这样起它)
+//! wake-mcp [--db PATH] [--on-request]
+//! 以 MCP server 身份服务 stdin/stdout(客户端这样起它)
//! wake-mcp setup [--db PATH] 打印接入 Claude Code / Codex / Cursor 的配置片段
//! wake-mcp call TOOL [JSON] 跑一次工具调用、打印文本(调试用)
//! wake-mcp --version | --help
@@ -12,26 +13,31 @@ use std::path::PathBuf;
use std::process::ExitCode;
use wake_core::db::Store;
-use wake_core::mcp::{self, McpServer};
+use wake_core::mcp::{self, McpServer, Usage};
const USAGE: &str = "wake-mcp — read-only MCP server for your Wake session index
USAGE:
- wake-mcp [--db PATH] serve MCP over stdio (what MCP clients run)
+ wake-mcp [--db PATH] [--on-request]
+ serve MCP over stdio (what MCP clients run)
wake-mcp setup [--db PATH] print config snippets for Claude Code / Codex / Cursor
wake-mcp call TOOL [JSON] run one tool call and print its text (debugging)
wake-mcp --version | --help
OPTIONS:
- --db PATH index database (default: Wake's own, e.g. ~/Library/Application Support/wake/wake.db)";
+ --db PATH index database (default: Wake's own, e.g. ~/Library/Application Support/wake/wake.db)
+ --on-request tell agents to use these tools only when you ask (same as WAKE_ON_REQUEST=1)";
struct Args {
db: Option<PathBuf>,
+ usage: Usage,
command: Vec<String>,
}
fn parse_args() -> Result<Args, String> {
let mut db = None;
+ // 参数压过环境变量
+ let mut usage = Usage::from_env();
let mut command = Vec::new();
let mut it = std::env::args().skip(1);
while let Some(a) = it.next() {
@@ -41,6 +47,7 @@ fn parse_args() -> Result<Args, String> {
it.next().ok_or("--db needs a path".to_string())?,
))
}
+ "--on-request" => usage = Usage::OnRequest,
"--help" | "-h" => {
println!("{USAGE}");
std::process::exit(0);
@@ -54,16 +61,16 @@ fn parse_args() -> Result<Args, String> {
_ => command.push(a),
}
}
- Ok(Args { db, command })
+ Ok(Args { db, usage, command })
}
fn db_path(db: &Option<PathBuf>) -> PathBuf {
wake_core::db::path_or_default(db.as_deref())
}
-fn open(db: &Option<PathBuf>) -> Result<McpServer, String> {
+fn open(db: &Option<PathBuf>, usage: Usage) -> Result<McpServer, String> {
let (store, adapters) = mcp::open_index(&db_path(db))?;
- Ok(McpServer::new(store, adapters))
+ Ok(McpServer::new(store, adapters, usage))
}
fn main() -> ExitCode {
@@ -76,7 +83,7 @@ fn main() -> ExitCode {
};
match args.command.first().map(String::as_str) {
None => {
- let server = match open(&args.db) {
+ let server = match open(&args.db, args.usage) {
Ok(s) => s,
Err(e) => {
eprintln!("wake-mcp: {e}");
@@ -121,7 +128,7 @@ fn main() -> ExitCode {
return ExitCode::from(2);
}
};
- let server = match open(&args.db) {
+ let server = match open(&args.db, args.usage) {
Ok(s) => s,
Err(e) => {
eprintln!("wake-mcp: {e}");
diff --git a/crates/wake-core/src/mcp/mod.rs b/crates/wake-core/src/mcp/mod.rs
index d8395e0..34360ff 100644
--- a/crates/wake-core/src/mcp/mod.rs
+++ b/crates/wake-core/src/mcp/mod.rs
@@ -32,20 +32,91 @@ const SUPPORTED: [&str; 4] = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11
pub const SERVER_NAME: &str = "wake";
pub const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
-/// 随 initialize 下发给客户端的使用说明(LLM 会读)。重点是"什么时候该用":
-/// 模型对陌生工具默认不碰,问"最近在做什么"会去翻 git log——要点明会话记录里
-/// 有而 git 里没有的东西(讨论、决策、试过的路、停在哪)
-const INSTRUCTIONS: &str = "Wake indexes every coding-agent session on this machine \
-(Claude Code, Codex, Cursor, Gemini CLI, OpenCode and more) and exposes them read-only. \
-Use these tools whenever the user refers to earlier conversations or sessions with any AI \
-coding agent: what was discussed, decided or tried, why something was done a certain way, \
-where previous work stopped, or whether an error was seen before. Git history and the \
-working tree do not contain that; Wake does. Start with wake_list_sessions (pass the \
-current working directory as `project`) or wake_search, then read the relevant transcript \
-with wake_get_session; wake_list_projects shows which projects have history. \
-wake_list_memories lists the notes agents keep for themselves about a project (Claude \
-Code and ZCode auto-memory, Codex memories); read one by passing its wake://memory/… \
-reference to wake_get_session. Nothing here can modify a session or a memory file.";
+/// agent 什么时候该用 Wake 的工具。默认 `Proactive`:用户提到之前的对话就用;`OnRequest`
+/// (`wake-mcp --on-request` / `WAKE_ON_REQUEST=1`,#64)只在用户明确让它查 Wake 或过去的会话
+/// 时才用——自己有记忆工具的人不想让 agent 为了回忆上下文自己去翻、花 token。只换下发给模型的
+/// 说明与工具描述里"什么时候用"那一句,工具本身与返回内容不变;这是给模型的指引,不是锁,
+/// 硬性拦住靠客户端的权限确认
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Usage {
+ Proactive,
+ OnRequest,
+}
+
+/// 插件用户改不了插件里的启动命令,靠这个环境变量打开 `Usage::OnRequest`;`wake-cli context`
+/// (开会话钩子)见到它也不输出——判法只有 `Usage::from_env` 这一份,钩子与 MCP 永远出自同一对
+/// 二进制,插件与 app 各自更新也不会一半生效
+pub const ON_REQUEST_ENV: &str = "WAKE_ON_REQUEST";
+
+impl Usage {
+ pub fn from_env() -> Self {
+ let value = std::env::var_os(ON_REQUEST_ENV);
+ // 不是 UTF-8 的值也是"设了"
+ Self::from_env_value(value.as_ref().map(|v| v.to_str().unwrap_or("1")))
+ }
+
+ /// 没设、空串、0 / false / no(不分大小写)是关,别的都是开
+ fn from_env_value(value: Option<&str>) -> Self {
+ match value.map(str::to_ascii_lowercase).as_deref() {
+ None | Some("" | "0" | "false" | "no") => Self::Proactive,
+ Some(_) => Self::OnRequest,
+ }
+ }
+
+ /// 一段给模型看的话 = 做什么 + 什么时候用 + 怎么用,只在被要求时使用只换中间那句(服务器说明与
+ /// 每个工具的描述共用,两种模式不各写一份全文)。`when` 为 None 的(wake_get_session 的描述没有
+ /// 触发句)默认就只有两段
+ pub(crate) fn compose(
+ self,
+ what: &str,
+ when: Option<&str>,
+ on_request: &str,
+ how: &str,
+ ) -> String {
+ let when = match self {
+ Self::Proactive => when,
+ Self::OnRequest => Some(on_request),
+ };
+ match when {
+ Some(when) => format!("{what} {when} {how}"),
+ None => format!("{what} {how}"),
+ }
+ }
+}
+
+/// 随 initialize 下发给客户端的使用说明(LLM 会读),三段拼成:是什么、什么时候用、怎么用。
+/// 默认那句是重点:模型对陌生工具默认不碰,问"最近在做什么"会去翻 git log——要点明会话
+/// 记录里有而 git 里没有的东西(讨论、决策、试过的路、停在哪)
+const INSTRUCTIONS_INTRO: &str = "Wake indexes every coding-agent session on this machine \
+(Claude Code, Codex, Cursor, Gemini CLI, OpenCode and more) and exposes them read-only.";
+const INSTRUCTIONS_WHEN: &str = "Use these tools whenever the user refers to earlier \
+conversations or sessions with any AI coding agent: what was discussed, decided or tried, \
+why something was done a certain way, where previous work stopped, or whether an error was \
+seen before. Git history and the working tree do not contain that; Wake does.";
+/// 只在被要求时使用换上的两句:服务器说明里一句、每个工具描述里一句,说的是同一件事,改一句
+/// 就一起改
+const INSTRUCTIONS_ON_REQUEST: &str = "The user wants these tools used only when they ask: \
+call them when the user explicitly asks you to look something up in Wake or in their past \
+sessions (\"check Wake\", \"search my past sessions for …\"), and don't call them on your \
+own to recall context.";
+pub(crate) const TOOL_ON_REQUEST: &str = "Call it only when the user explicitly asks you to \
+look something up in Wake or in their past sessions; don't call it on your own to recall \
+context.";
+const INSTRUCTIONS_HOW: &str = "Start with wake_list_sessions (pass the current working \
+directory as `project`) or wake_search, then read the relevant transcript with \
+wake_get_session; wake_list_projects shows which projects have history. wake_list_memories \
+lists the notes agents keep for themselves about a project (Claude Code and ZCode \
+auto-memory, Codex memories); read one by passing its wake://memory/… reference to \
+wake_get_session. Nothing here can modify a session or a memory file.";
+
+pub fn instructions(usage: Usage) -> String {
+ usage.compose(
+ INSTRUCTIONS_INTRO,
+ Some(INSTRUCTIONS_WHEN),
+ INSTRUCTIONS_ON_REQUEST,
+ INSTRUCTIONS_HOW,
+ )
+}
const JSONRPC_PARSE_ERROR: i64 = -32700;
const JSONRPC_INVALID_REQUEST: i64 = -32600;
@@ -58,14 +129,16 @@ pub struct McpServer {
store: Arc<Store>,
adapters: Vec<Box<dyn AgentAdapter>>,
transcripts: tools::TranscriptCache,
+ usage: Usage,
}
impl McpServer {
- pub fn new(store: Arc<Store>, adapters: Vec<Box<dyn AgentAdapter>>) -> Self {
+ pub fn new(store: Arc<Store>, adapters: Vec<Box<dyn AgentAdapter>>, usage: Usage) -> Self {
Self {
store,
adapters,
transcripts: tools::TranscriptCache::default(),
+ usage,
}
}
@@ -155,7 +228,7 @@ impl McpServer {
let result = match method {
"initialize" => Ok(self.initialize(&params)),
"ping" => Ok(json!({})),
- "tools/list" => Ok(json!({ "tools": tools::definitions() })),
+ "tools/list" => Ok(json!({ "tools": tools::definitions_for(self.usage) })),
"tools/call" => self.call_tool(&params),
_ => Err((
JSONRPC_METHOD_NOT_FOUND,
@@ -182,7 +255,7 @@ impl McpServer {
"protocolVersion": version,
"capabilities": { "tools": { "listChanged": false } },
"serverInfo": { "name": SERVER_NAME, "title": "Wake", "version": SERVER_VERSION },
- "instructions": INSTRUCTIONS,
+ "instructions": instructions(self.usage),
})
}
@@ -307,8 +380,32 @@ mod tests {
/// 时漏了这里)
#[test]
fn instructions_mention_every_tool() {
- for name in tools::NAMES {
- assert!(INSTRUCTIONS.contains(name), "INSTRUCTIONS 没提到 {name}");
+ for usage in [Usage::Proactive, Usage::OnRequest] {
+ let text = instructions(usage);
+ for name in tools::NAMES {
+ assert!(text.contains(name), "{usage:?} 的说明没提到 {name}");
+ }
+ }
+ }
+
+ /// 只在被要求时使用:只换"什么时候用"那一句,开头与用法照旧
+ #[test]
+ fn on_request_only_changes_when_to_use() {
+ let proactive = instructions(Usage::Proactive);
+ assert!(proactive.contains(INSTRUCTIONS_WHEN));
+ assert_eq!(
+ instructions(Usage::OnRequest),
+ proactive.replace(INSTRUCTIONS_WHEN, INSTRUCTIONS_ON_REQUEST)
+ );
+ }
+
+ #[test]
+ fn the_on_request_switch_reads_like_a_flag() {
+ for off in [None, Some(""), Some("0"), Some("false"), Some("No")] {
+ assert_eq!(Usage::from_env_value(off), Usage::Proactive, "{off:?}");
+ }
+ for on in ["1", "true", "YES", "on"] {
+ assert_eq!(Usage::from_env_value(Some(on)), Usage::OnRequest, "{on}");
}
}
diff --git a/crates/wake-core/src/mcp/tools.rs b/crates/wake-core/src/mcp/tools.rs
index 5094825..fb9bd0c 100644
--- a/crates/wake-core/src/mcp/tools.rs
+++ b/crates/wake-core/src/mcp/tools.rs
@@ -17,6 +17,8 @@ use crate::services::context::{parse_since, resolve_project_paths};
use crate::services::exporter::{fmt_time, render_compact, CompactOptions};
use crate::text::{one_line, plural};
+use super::{Usage, TOOL_ON_REQUEST};
+
struct ToolContext<'a> {
store: &'a Store,
adapters: &'a [Box<dyn AgentAdapter>],
@@ -153,13 +155,25 @@ fn since_param() -> Value {
})
}
-/// tools/list 的内容。名字、参数名是对外契约,改了别人的配置就失效
+/// tools/list 的内容(默认模式)。名字、参数名是对外契约,改了别人的配置就失效;CLI 只读这里的
+/// schema(帮助里的默认值与上限、与 COMMANDS 的双射)
pub fn definitions() -> Vec<Value> {
+ definitions_for(Usage::Proactive)
+}
+
+/// 按 `Usage` 给的 tools/list:两种模式只差描述里"什么时候用"那一句(`Usage::compose`)
+pub fn definitions_for(usage: Usage) -> Vec<Value> {
+ let describe =
+ |what: &str, when: Option<&str>, how: &str| usage.compose(what, when, TOOL_ON_REQUEST, how);
vec![
json!({
"name": SEARCH,
"title": "Search session history",
- "description": "Full-text search across every indexed coding-agent session on this machine (session titles, user prompts, assistant replies, tool names and inputs). Use it when the user asks whether something was discussed, tried or solved before, or wants the conversation about a topic, an error message, a file or a decision — git history does not hold that. Terms are ANDed; CJK text and code substrings like `useEffect(` work. Returns matching sessions with up to three snippets each, plus a `wake://session/<key>#<seq>` reference per snippet that you can read with wake_get_session.",
+ "description": describe(
+ "Full-text search across every indexed coding-agent session on this machine (session titles, user prompts, assistant replies, tool names and inputs).",
+ Some("Use it when the user asks whether something was discussed, tried or solved before, or wants the conversation about a topic, an error message, a file or a decision — git history does not hold that."),
+ "Terms are ANDed; CJK text and code substrings like `useEffect(` work. Returns matching sessions with up to three snippets each, plus a `wake://session/<key>#<seq>` reference per snippet that you can read with wake_get_session.",
+ ),
"inputSchema": {
"type": "object",
"properties": {
@@ -176,7 +190,11 @@ pub fn definitions() -> Vec<Value> {
json!({
"name": LIST_SESSIONS,
"title": "List recent sessions",
- "description": "Most recently updated coding-agent sessions, optionally scoped to a project, to some agents, to a time window, or to starred sessions. Use it when the user asks what they or an agent worked on recently, wants to resume or continue earlier work, or refers to \"yesterday's session\", \"last time\", \"what Codex did here\" — pass the current working directory as `project`. It returns the session keys wake_get_session needs. Subagent sessions are folded into their parents; archived sessions are excluded.",
+ "description": describe(
+ "Most recently updated coding-agent sessions, optionally scoped to a project, to some agents, to a time window, or to starred sessions.",
+ Some("Use it when the user asks what they or an agent worked on recently, wants to resume or continue earlier work, or refers to \"yesterday's session\", \"last time\", \"what Codex did here\"."),
+ "Pass the current working directory as `project`. It returns the session keys wake_get_session needs. Subagent sessions are folded into their parents; archived sessions are excluded.",
+ ),
"inputSchema": {
"type": "object",
"properties": {
@@ -192,7 +210,12 @@ pub fn definitions() -> Vec<Value> {
json!({
"name": GET_SESSION,
"title": "Read a session transcript",
- "description": "Read one session's transcript, parsed live from the agent's own files, as compact Markdown: user and assistant messages with `[seq N]` markers, tool calls folded to one line each, injected context omitted. Use it after wake_search or wake_list_sessions to see what actually happened — the reasoning, the decisions and the exact steps of an earlier session. Paginated: when the reply ends with a `from_seq` hint, call again with it to continue. Accepts a session key or a `wake://session/<key>#<seq>` reference (the seq becomes the starting point). Subagent transcripts (Claude Code sidechains, Cursor subagents) are listed at the end of the main transcript; pass one's id as `subagent` to read it. Also reads memory files: pass a `wake://memory/<key>` reference from wake_list_memories or wake_search to get that file.",
+ // "Use it after …" 说的是先后,不是什么时候该查:两种模式都留着
+ "description": describe(
+ "Read one session's transcript, parsed live from the agent's own files, as compact Markdown: user and assistant messages with `[seq N]` markers, tool calls folded to one line each, injected context omitted.",
+ None,
+ "Use it after wake_search or wake_list_sessions to see what actually happened — the reasoning, the decisions and the exact steps of an earlier session. Paginated: when the reply ends with a `from_seq` hint, call again with it to continue. Accepts a session key or a `wake://session/<key>#<seq>` reference (the seq becomes the starting point). Subagent transcripts (Claude Code sidechains, Cursor subagents) are listed at the end of the main transcript; pass one's id as `subagent` to read it. Also reads memory files: pass a `wake://memory/<key>` reference from wake_list_memories or wake_search to get that file.",
+ ),
"inputSchema": {
"type": "object",
"properties": {
@@ -212,7 +235,11 @@ pub fn definitions() -> Vec<Value> {
json!({
"name": LIST_PROJECTS,
"title": "List indexed projects",
- "description": "Projects (working directories) that have coding-agent session history, most recently active first, with session counts. Use it when the user asks broadly what they have been working on (\"which projects did I touch this month?\") or to find the right `project` value for the other tools.",
+ "description": describe(
+ "Projects (working directories) that have coding-agent session history, most recently active first, with session counts.",
+ Some("Use it when the user asks broadly what they have been working on (\"which projects did I touch this month?\")."),
+ "It also gives the right `project` value for the other tools.",
+ ),
"inputSchema": {
"type": "object",
"properties": {
@@ -225,7 +252,11 @@ pub fn definitions() -> Vec<Value> {
json!({
"name": LIST_MEMORIES,
"title": "List agent memory files",
- "description": "The memory files coding agents keep for themselves on this machine — Claude Code's and ZCode's per-project auto-memory (MEMORY.md and its topic files), Codex's memories — plus the instruction files the user keeps for them (CLAUDE.md, AGENTS.md, GEMINI.md, .cursor/rules, .kiro/steering, copilot-instructions.md), read-only, grouped by project, user memory (the notes that apply to every project) last. Use it when the user asks what an agent already knows or remembers about a project, or to reuse another agent's notes: decisions, conventions, gotchas. Each entry ends with a `wake://memory/<key>` reference; read one with wake_get_session.",
+ "description": describe(
+ "The memory files coding agents keep for themselves on this machine — Claude Code's and ZCode's per-project auto-memory (MEMORY.md and its topic files), Codex's memories — plus the instruction files the user keeps for them (CLAUDE.md, AGENTS.md, GEMINI.md, .cursor/rules, .kiro/steering, copilot-instructions.md), read-only, grouped by project, user memory (the notes that apply to every project) last.",
+ Some("Use it when the user asks what an agent already knows or remembers about a project, or to reuse another agent's notes: decisions, conventions, gotchas."),
+ "Each entry ends with a `wake://memory/<key>` reference; read one with wake_get_session.",
+ ),
"inputSchema": {
"type": "object",
"properties": {
@@ -1579,4 +1610,21 @@ mod tests {
assert_eq!(d["annotations"]["readOnlyHint"], true);
}
}
+
+ /// 只在被要求时使用:每个工具都带那句限定、不再有"Use it when"一类的触发说法,别的
+ /// (名字、参数、注解)与默认逐字相同
+ #[test]
+ fn on_request_descriptions_only_swap_when_to_use() {
+ let strip = |d: &Value| {
+ let mut d = d.clone();
+ d.as_object_mut().unwrap().remove("description");
+ d
+ };
+ for (default, asked) in definitions().iter().zip(&definitions_for(Usage::OnRequest)) {
+ let text = asked["description"].as_str().unwrap();
+ assert!(text.contains(TOOL_ON_REQUEST), "{text}");
+ assert!(!text.contains("Use it when"), "{text}");
+ assert_eq!(strip(default), strip(asked));
+ }
+ }
}
diff --git a/crates/wake-core/tests/cli.rs b/crates/wake-core/tests/cli.rs
index 9037c48..4bc8d16 100644
--- a/crates/wake-core/tests/cli.rs
+++ b/crates/wake-core/tests/cli.rs
@@ -18,6 +18,7 @@ use wake_core::adapters::{create_adapter_roster_for, create_adapters_for, AgentA
use wake_core::cli;
use wake_core::db::{self, Store};
use wake_core::mcp::tools::{self, TranscriptCache};
+use wake_core::mcp::ON_REQUEST_ENV;
use wake_core::models::{AgentId, Role, SessionFilter, SessionMeta};
use wake_core::scanner::{run_scan, NullEvents};
@@ -832,10 +833,19 @@ fn context_shows_where_each_agent_left_off_or_nothing() {
);
write("claude-code:in-home", &home, 0, &[(Role::User, "hi")]);
}
+ // 跑测试的环境里设了 WAKE_ON_REQUEST 也清掉,默认那套才是确定的
+ let context_with = |dir: &Path, on_request: Option<&str>| {
+ cli_raw_with(&["--db", db.to_str().unwrap(), "context"], |cmd| {
+ cmd.env("WAKE_HOME", &home)
+ .env_remove(ON_REQUEST_ENV)
+ .current_dir(dir);
+ if let Some(value) = on_request {
+ cmd.env(ON_REQUEST_ENV, value);
+ }
+ })
+ };
let context = |dir: &Path| {
- let (out, _, code) = cli_raw_with(&["--db", db.to_str().unwrap(), "context"], |cmd| {
- cmd.env("WAKE_HOME", &home).current_dir(dir);
- });
+ let (out, _, code) = context_with(dir, None);
(out, code)
};
let (text, code) = context(&project.join("src"));
@@ -879,6 +889,12 @@ fn context_shows_where_each_agent_left_off_or_nothing() {
for dir in [fresh.as_path(), elsewhere.path()] {
assert_eq!(context(dir), (String::new(), Some(0)), "{}", dir.display());
}
+
+ // 只在被要求时使用(#64):开会话什么都不加,stderr 那句只给在终端里自己跑的人看;写 0 是关
+ let (out, err, code) = context_with(&project, Some("1"));
+ assert_eq!((out.as_str(), code), ("", Some(0)));
+ assert!(err.contains(ON_REQUEST_ENV), "{err}");
+ assert_eq!(context_with(&project, Some("0")).0, text);
}
/// 插件只是一层壳:清单、钩子、MCP 配置都指向仓库里真实存在的脚本,钩子调的是 `wake-cli
@@ -926,7 +942,7 @@ fn the_plugins_point_at_real_files() {
// Codex 不展开 MCP 参数里的变量(只展开钩子命令),写相对路径 + cwd "."(插件根,Codex
// 自带的插件也这么写),直接放在清单里。Codex 只给 MCP 子进程几个默认环境变量(PATH、
// HOME 这些),启动脚本认的 WAKE_BIN_DIR 要点名放行,不然 Wake 装在别处的人钩子能用、
- // MCP 却找不到 wake-mcp
+ // MCP 却找不到 wake-mcp;WAKE_ON_REQUEST 同理,不放行 wake-mcp 就看不见它
let mcp = json(plugin.join(".mcp.json"));
let args = &mcp["mcpServers"]["wake"]["args"];
assert_eq!(args[0], "${CLAUDE_PLUGIN_ROOT}/scripts/wake");
@@ -948,7 +964,7 @@ fn the_plugins_point_at_real_files() {
"command": "sh",
"args": ["./scripts/wake", "wake-mcp"],
"cwd": ".",
- "env_vars": ["WAKE_BIN_DIR"]
+ "env_vars": ["WAKE_BIN_DIR", ON_REQUEST_ENV]
})
);
for field in ["logo", "composerIcon"] {
diff --git a/crates/wake-core/tests/mcp_stdio.rs b/crates/wake-core/tests/mcp_stdio.rs
index 2f83c47..2d1d5af 100644
--- a/crates/wake-core/tests/mcp_stdio.rs
+++ b/crates/wake-core/tests/mcp_stdio.rs
@@ -14,6 +14,7 @@ use std::sync::Arc;
use serde_json::{json, Value};
use wake_core::adapters::{adapter_for, create_adapter_roster_for};
use wake_core::db::Store;
+use wake_core::mcp::{self, tools, Usage, ON_REQUEST_ENV};
use wake_core::models::*;
use wake_core::scanner::{run_scan, NullEvents};
@@ -31,14 +32,21 @@ struct Client {
impl Client {
fn spawn(db: &Path) -> Client {
- let mut child = Command::new(env!("CARGO_BIN_EXE_wake-mcp"))
- .arg("--db")
+ Self::spawn_with(db, |_| {})
+ }
+
+ /// `with` 加参数、设环境变量。跑测试的环境里设了 WAKE_ON_REQUEST 也先清掉,默认那套说明
+ /// 才是确定的
+ fn spawn_with(db: &Path, with: impl FnOnce(&mut Command)) -> Client {
+ let mut cmd = Command::new(env!("CARGO_BIN_EXE_wake-mcp"));
+ cmd.arg("--db")
.arg(db)
+ .env_remove(ON_REQUEST_ENV)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()
- .expect("spawn wake-mcp");
+ .stderr(Stdio::null());
+ with(&mut cmd);
+ let mut child = cmd.spawn().expect("spawn wake-mcp");
let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());
Client {
@@ -75,6 +83,17 @@ impl Client {
reply
}
+ fn initialize(&mut self) -> Value {
+ self.request(
+ "initialize",
+ json!({
+ "protocolVersion": "2025-06-18",
+ "capabilities": {},
+ "clientInfo": { "name": "wake-test", "version": "0" }
+ }),
+ )
+ }
+
fn notify(&mut self, method: &str) {
self.send_raw(&json!({ "jsonrpc": "2.0", "method": method }).to_string());
}
@@ -175,14 +194,7 @@ fn stdio_contract_end_to_end() {
// 2. 握手与协议面
let mut c = Client::spawn(&db);
- let init = c.request(
- "initialize",
- json!({
- "protocolVersion": "2025-06-18",
- "capabilities": {},
- "clientInfo": { "name": "wake-test", "version": "0" }
- }),
- );
+ let init = c.initialize();
assert_eq!(init["result"]["protocolVersion"], "2025-06-18");
assert_eq!(init["result"]["serverInfo"]["name"], "wake");
assert!(init["result"]["capabilities"]["tools"].is_object());
@@ -441,6 +453,41 @@ fn stdio_contract_end_to_end() {
assert!(before == after, "wake-mcp must never write the index");
}
+/// 只在被要求时使用(#64):`--on-request` 与 WAKE_ON_REQUEST=1 都换上这个模式的说明与工具描述,
+/// 都不给是默认那套——拿库里同一份文字比,措辞改了这里不用跟着改
+#[test]
+fn on_request_mode_tells_agents_to_wait_until_asked() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = tmp.path().join("wake.db");
+ drop(Store::open(&db).unwrap());
+ let handshake = |with: &dyn Fn(&mut Command)| {
+ let mut c = Client::spawn_with(&db, with);
+ let instructions = c.initialize()["result"]["instructions"].clone();
+ let tools = c.request("tools/list", json!({}))["result"]["tools"].clone();
+ c.finish();
+ (instructions, tools)
+ };
+ let expect = |usage| {
+ (
+ json!(mcp::instructions(usage)),
+ json!(tools::definitions_for(usage)),
+ )
+ };
+ assert_eq!(handshake(&|_| {}), expect(Usage::Proactive));
+ assert_eq!(
+ handshake(&|cmd| {
+ cmd.arg("--on-request");
+ }),
+ expect(Usage::OnRequest)
+ );
+ assert_eq!(
+ handshake(&|cmd| {
+ cmd.env(ON_REQUEST_ENV, "1");
+ }),
+ expect(Usage::OnRequest)
+ );
+}
+
#[test]
fn missing_index_exits_with_a_clear_error() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/docs/cli.md b/docs/cli.md
index e3411f9..ecd8360 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -150,7 +150,8 @@ It is what the [Claude Code plugin](#claude-code-plugin) and the [Codex plugin](
prints lands in the new session's context, where a "no sessions" reply or a list of other
projects would only be noise. A subfolder counts as its project, as with `--project
"$PWD"`. Your home folder and the filesystem root never count as the project a folder
-belongs to — sessions started there are not about the project you open next.
+belongs to — sessions started there are not about the project you open next. With
+`WAKE_ON_REQUEST` on, it prints nothing (see [Only when you ask](mcp.md#only-when-you-ask)).
### `index`
@@ -378,6 +379,9 @@ For both:
its own history, so the hook stays out of those.
- A lookup made by the hook is not the agent asking Wake, so it does not show up in
Insights under *Agents asking Wake*; the lookups the agent then makes on its own do.
+- To keep Wake quiet until you ask, set `WAKE_ON_REQUEST=1` in the environment Claude Code
+ or Codex starts from: the session-start hook adds nothing, and the agent uses Wake's
+ tools only when you ask (see [Only when you ask](mcp.md#only-when-you-ask)).
- None of this edits another tool's configuration: Claude Code and Codex install the plugin
themselves, and the hook settings are yours to paste.
- On Windows, use the skill and the MCP server for now.
diff --git a/docs/mcp.md b/docs/mcp.md
index ee0fa3d..36940c0 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -110,6 +110,27 @@ that runs `wake-cli context`; see
[Claude Code plugin](cli.md#claude-code-plugin) and [Codex plugin](cli.md#codex-plugin) in the
command-line guide. Both plugins bring this MCP server along.
+### Only when you ask
+
+If your agent already keeps its own memory and you would rather it look in Wake only when
+you say so, start the server with `--on-request`:
+
+```bash
+claude mcp add --scope user wake -- "/Applications/Wake.app/Contents/MacOS/wake-mcp" --on-request
+```
+
+For Codex, add `args = ["--on-request"]` under `[mcp_servers.wake]`; for Cursor, add
+`"args": ["--on-request"]` next to `command`. With the Claude Code or Codex plugin, set
+`WAKE_ON_REQUEST=1` in the environment the agent starts from instead. The plugin then also
+skips the recent sessions it adds when a session starts.
+
+In this mode the server tells the agent to use its tools only when you ask it to look
+something up in Wake or in your past sessions ("check Wake for …"). The agent follows that
+as guidance; it is not a lock. To stop calls outright, have your client ask before each
+one (in Claude Code, keep the wake tools out of `permissions.allow`), or turn the server
+off in `/mcp` until you need it. The line from *Make the agent reach for it* and the Wake
+skill ask for the opposite, so leave them out.
+
### A worked example
```
diff --git a/plugins/wake/.codex-plugin/plugin.json b/plugins/wake/.codex-plugin/plugin.json
index 3bdad0a..a110a18 100644
--- a/plugins/wake/.codex-plugin/plugin.json
+++ b/plugins/wake/.codex-plugin/plugin.json
@@ -25,7 +25,8 @@
],
"cwd": ".",
"env_vars": [
- "WAKE_BIN_DIR"
+ "WAKE_BIN_DIR",
+ "WAKE_ON_REQUEST"
]
}
},