From 6132171791ed3c7f2ec7a5effa49f7e9a395fa79 Mon Sep 17 00:00:00 2001 From: Gregory Schier Date: Sun, 25 Oct 2026 23:14:45 -0700 Subject: [PATCH] Agents pane: CLI-only MCP, `yaak mcp --http`, and plugin deprecation (#761) --- .../components/Settings/Settings.tsx | 2 - .../components/Settings/SettingsAgents.tsx | 245 +++++--------- .../components/Settings/SettingsPlugins.tsx | 134 +++++--- .../components/core/SettingRow.tsx | 85 +++++ apps/yaak-client/hooks/usePluginInfo.ts | 18 +- apps/yaak-client/hooks/useUninstallPlugin.tsx | 31 ++ apps/yaak-client/lib/agentSetup.test.ts | 58 ++-- apps/yaak-client/lib/agentSetup.ts | 77 ++--- crates-cli/yaak-cli/src/cli.rs | 19 +- crates-cli/yaak-cli/src/commands/mcp.rs | 49 ++- crates-cli/yaak-cli/src/main.rs | 5 +- crates-cli/yaak-cli/tests/mcp_command.rs | 126 +++++++ crates-tauri/yaak-app-client/src/lib.rs | 2 - crates-tauri/yaak-app-client/src/mcp_ext.rs | 192 ----------- .../yaak-app-client/src/models_ext.rs | 6 - crates-tauri/yaak-app-client/src/rpc_ext.rs | 8 + .../yaak-rpc-schema/bindings/gen_rpc.ts | 15 +- .../yaak-rpc-schema/bindings/gen_search.ts | 8 +- crates/common/yaak-rpc-schema/src/lib.rs | 30 ++ crates/yaak-commands/src/agents.rs | 317 ++++++++++++++++++ crates/yaak-commands/src/lib.rs | 1 + crates/yaak-commands/src/plugins.rs | 1 + crates/yaak-mcp/src/lib.rs | 3 +- crates/yaak-plugins/bindings/gen_search.ts | 8 +- crates/yaak-plugins/src/api.rs | 3 + crates/yaak-plugins/src/plugin_meta.rs | 4 + packages/platform/src/types.ts | 2 +- .../src/bindings/gen_models.ts | 1 + .../src/bindings/gen_search.ts | 8 +- plugins-external/mcp-server/README.md | 11 +- plugins-external/mcp-server/package.json | 3 +- plugins-external/mcp-server/src/index.ts | 2 +- 32 files changed, 950 insertions(+), 524 deletions(-) create mode 100644 apps/yaak-client/hooks/useUninstallPlugin.tsx delete mode 100644 crates-tauri/yaak-app-client/src/mcp_ext.rs create mode 100644 crates/yaak-commands/src/agents.rs diff --git a/apps/yaak-client/components/Settings/Settings.tsx b/apps/yaak-client/components/Settings/Settings.tsx index 5c8c0fb68..1039ce74f 100644 --- a/apps/yaak-client/components/Settings/Settings.tsx +++ b/apps/yaak-client/components/Settings/Settings.tsx @@ -123,8 +123,6 @@ export default function Settings({ tab, hide }: Props) { ) : value === TAB_PLUGINS ? ( p.source !== "bundled").length} /> - ) : value === TAB_AGENTS && settings.mcpServerEnabled ? ( - ) : value === TAB_PROXY && settings.proxy?.type === "enabled" ? ( ) : value === TAB_LICENSE && licenseCheck.check.data?.status === "personal_use" ? ( diff --git a/apps/yaak-client/components/Settings/SettingsAgents.tsx b/apps/yaak-client/components/Settings/SettingsAgents.tsx index 102d53705..4ba04091c 100644 --- a/apps/yaak-client/components/Settings/SettingsAgents.tsx +++ b/apps/yaak-client/components/Settings/SettingsAgents.tsx @@ -1,145 +1,72 @@ -import { useQuery } from "@tanstack/react-query"; -import { settingsAtom } from "@yaakapp-internal/models"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; import { platform } from "@yaakapp-internal/platform"; -import { Heading, Icon, InlineCode, VStack } from "@yaakapp-internal/ui"; -import type { AppMetaData } from "@yaakapp-internal/rpc-schema"; -import { useAtomValue } from "jotai"; +import type { AgentSetupStatus, AppMetaData } from "@yaakapp-internal/rpc-schema"; +import { Banner, Heading, Icon, InlineCode, VStack } from "@yaakapp-internal/ui"; +import { useEffect } from "react"; import { useKeyValue } from "../../hooks/useKeyValue"; -import { appInfo } from "../../lib/appInfo"; +import { usePluginInfos } from "../../hooks/usePluginInfo"; import { AGENT_CLIENTS, type AgentClient, - type AgentSetup, - appSetup, cliSetup, + skillInstallCommand, } from "../../lib/agentSetup"; +import { appInfo } from "../../lib/appInfo"; import { rpc } from "../../lib/rpc"; -import { CopyIconButton } from "../CopyIconButton"; -import { Button } from "../core/Button"; -import { Editor } from "../core/Editor/LazyEditor"; -import { IconButton } from "../core/IconButton"; +import { Link } from "../core/Link"; import { SegmentedControl } from "../core/SegmentedControl"; import { - ModelSettingRowBoolean, - SettingRow, - SettingValue, + SettingCommand, + SettingSnippet, SettingsList, SettingsSection, } from "../core/SettingRow"; +import { DeprecatedPluginBanner } from "./SettingsPlugins"; -const MCP_URL = "http://127.0.0.1:64343/mcp"; const CLI_INSTALL_COMMAND = "npm install -g @yaakapp/cli"; -const SKILL_INSTALL_COMMAND = "yaak agent install"; +const MCP_SERVER_PLUGIN = "@yaak/mcp-server"; export function SettingsAgents() { - const settings = useAtomValue(settingsAtom); - const { value: token } = useKeyValue({ - namespace: "no_sync", - key: "mcp_server_token", - fallback: null, - }); + const queryClient = useQueryClient(); const { value: storedClient, set: setClient } = useKeyValue({ key: "agents_setup_client", fallback: "claude_code", }); const client = AGENT_CLIENTS.find((c) => c.value === storedClient)?.value ?? "claude_code"; + const clientLabel = AGENT_CLIENTS.find((c) => c.value === client)?.label ?? "your agent"; const cliVersion = useQuery({ queryKey: ["cli_version"], queryFn: async () => (await rpc("cmd_metadata")).cliVersion, initialData: appInfo.cliVersion, }); + const setupStatus = useQuery({ + queryKey: ["agent_setup_status", client], + queryFn: () => rpc("cmd_agent_setup_status", { agent: client }), + }); + const mcpServerPlugin = usePluginInfos().find(({ info }) => info.name === MCP_SERVER_PLUGIN); + + useEffect(() => { + return platform.window.onFocusChanged((focused) => { + if (!focused) return; + void queryClient.invalidateQueries({ queryKey: ["cli_version"] }); + void queryClient.invalidateQueries({ queryKey: ["agent_setup_status"] }); + }); + }, [queryClient]); + + const cliInstalled = cliVersion.data != null; + const cli = cliSetup(client); return (
Agents

- Connect AI coding agents like Claude Code and Cursor to Yaak, so they can read, edit, and - send your requests. + Connect AI coding agents like Claude Code and Cursor to Yaak.

- - - - cliVersion.refetch()} - /> - {cliVersion.data == null && ( - - )} - - {cliVersion.data == null ? ( - - - - ) : ( - - Teach Claude Code, Cursor, Codex, and opencode to drive the{" "} - yaak command, wherever they're installed. - - } - > - - - )} - - - - - Serve Yaak's tools at {MCP_URL} while Yaak is open. - - } - /> - {settings.mcpServerEnabled && token != null && ( - - - - )} - - - -
+ + +
- - {settings.mcpServerEnabled && token != null ? ( - + {cliInstalled ? ( +
+ + + Yaak CLI {cliVersion.data} is installed. + +
) : ( - - - +
+ +
+ + Install the Yaak CLI first +
+

+ Agents launch it to reach Yaak, even with the app closed. +

+ +
+ Docs + + Checks again when you come back to Yaak. + +
+
+
)} + {mcpServerPlugin != null && ( +
+ + The two steps below replace it. Uninstall it once your agent is connected. + +
+ )} + + + Lets {clientLabel} run the yaak command directly. + + } + snippet={skillInstallCommand(client)} + language="shell" + disabled={!cliInstalled} + done={setupStatus.data?.skill ? "Installed" : null} + />
); } - -function SetupRow({ - title, - description, - setup, -}: { - title: string; - description: string; - setup: AgentSetup; -}) { - return ( -
-
{title}
-
{description}
- } - /> -
- ); -} diff --git a/apps/yaak-client/components/Settings/SettingsPlugins.tsx b/apps/yaak-client/components/Settings/SettingsPlugins.tsx index 225ab7518..d9bdcaa6c 100644 --- a/apps/yaak-client/components/Settings/SettingsPlugins.tsx +++ b/apps/yaak-client/components/Settings/SettingsPlugins.tsx @@ -2,13 +2,9 @@ import { useMutation, useQuery } from "@tanstack/react-query"; import type { Plugin } from "@yaakapp-internal/models"; import { patchModel, pluginsAtom } from "@yaakapp-internal/models"; import type { PluginVersion } from "@yaakapp-internal/plugins"; +import { checkPluginUpdates, installPlugin, searchPlugins } from "@yaakapp-internal/plugins"; import { - checkPluginUpdates, - installPlugin, - searchPlugins, - uninstallPlugin, -} from "@yaakapp-internal/plugins"; -import { + Banner, HStack, Icon, InlineCode, @@ -24,12 +20,11 @@ import { } from "@yaakapp-internal/ui"; import classNames from "classnames"; import { useAtomValue } from "jotai"; -import { useState } from "react"; +import { type ReactNode, useState } from "react"; import { useInstallPlugin } from "../../hooks/useInstallPlugin"; -import { usePluginInfo } from "../../hooks/usePluginInfo"; +import { usePluginInfo, usePluginInfos } from "../../hooks/usePluginInfo"; import { usePluginsKey, useRefreshPlugins } from "../../hooks/usePlugins"; -import { showConfirmDelete } from "../../lib/confirm"; -import { minPromiseMillis } from "../../lib/minPromiseMillis"; +import { usePromptUninstallPlugin } from "../../hooks/useUninstallPlugin"; import { Button } from "../core/Button"; import { Checkbox } from "../core/Checkbox"; import { IconButton } from "../core/IconButton"; @@ -205,7 +200,7 @@ function PluginTableRow({ mutationKey: ["install_plugin", name], mutationFn: (name: string) => installPlugin(name, null), }); - const uninstall = usePromptUninstall(plugin?.id ?? null, displayName); + const uninstall = usePromptUninstallPlugin(plugin?.id ?? null, displayName); const refreshPlugins = useRefreshPlugins(); return ( @@ -296,7 +291,10 @@ function PluginSearch() { const debouncedQuery = useDebouncedValue(query); const results = useQuery({ queryKey: ["plugins", debouncedQuery], - queryFn: () => searchPlugins(query), + queryFn: async () => { + const { plugins } = await searchPlugins(query); + return { plugins: plugins.filter((p) => p.deprecated == null) }; + }, }); return ( @@ -349,22 +347,77 @@ function InstalledPlugins({ plugins, className }: { plugins: Plugin[]; className
) : ( - - - - - Display Name - Name - Version - - - - - {plugins.map((p) => ( - - ))} - -
+
+ + + + + + Display Name + Name + Version + + + + + {plugins.map((p) => ( + + ))} + +
+
+ ); +} + +function DeprecatedPluginBanners() { + const deprecated = usePluginInfos().filter( + ({ plugin, info }) => plugin.source !== "bundled" && info.deprecated != null, + ); + return ( +
0 && "pb-3")}> + {deprecated.map(({ plugin, info }) => ( + + {withInlineCode(info.deprecated ?? "")} + + ))} +
+ ); +} + +/** Backtick spans in a package.json string, set as code. */ +function withInlineCode(text: string): ReactNode { + return text + .split("`") + .map((part, i) => (i % 2 === 1 ? {part} : part)); +} + +export function DeprecatedPluginBanner({ + children, + name, + plugin, +}: { + children: ReactNode; + name: string; + plugin: Plugin; +}) { + const uninstall = usePromptUninstallPlugin(plugin.id, name); + return ( + +
+
The {name} plugin is deprecated.
+

{children}

+
+ +
); } @@ -393,31 +446,6 @@ function BundledPlugins({ plugins }: { plugins: Plugin[] }) { ); } -function usePromptUninstall(pluginId: string | null, name: string) { - const mut = useMutation({ - mutationKey: ["uninstall_plugin", pluginId], - mutationFn: async () => { - if (pluginId == null) return; - - const confirmed = await showConfirmDelete({ - id: `uninstall-plugin-${pluginId}`, - title: "Uninstall Plugin", - confirmText: "Uninstall", - description: ( - <> - Permanently uninstall {name}? - - ), - }); - if (confirmed) { - await minPromiseMillis(uninstallPlugin(pluginId), 700); - } - }, - }); - - return pluginId == null ? null : mut; -} - function usePluginUpdates() { return useQuery({ queryKey: ["plugin_updates", usePluginsKey()], diff --git a/apps/yaak-client/components/core/SettingRow.tsx b/apps/yaak-client/components/core/SettingRow.tsx index bc463e610..a3c6f6c63 100644 --- a/apps/yaak-client/components/core/SettingRow.tsx +++ b/apps/yaak-client/components/core/SettingRow.tsx @@ -1,5 +1,6 @@ import type { AnyModel } from "@yaakapp-internal/models"; import { patchModel } from "@yaakapp-internal/models"; +import { Icon } from "@yaakapp-internal/ui"; import classNames from "classnames"; import type { ReactNode } from "react"; import { CopyIconButton } from "../CopyIconButton"; @@ -139,6 +140,90 @@ export function SettingValue({ ); } +/** + * A command or config to copy, set as a block: its title, an optional line + * saying which file it goes in, then the snippet at full width with the copy + * button on it. One-line shell commands and multi-line JSON get the same block. + */ +export function SettingCommand({ + className, + description, + disabled, + done, + language, + snippet, + title, +}: { + description?: ReactNode; + disabled?: boolean; + /** A short word shown with a check beside the title once the step is detected as done */ + done?: ReactNode; + language: SettingSnippetLanguage; + snippet: string; + title: ReactNode; +} & Pick) { + return ( +
+
+ {title} + {done != null && done !== false && ( + + + {done} + + )} +
+ {description != null && ( +
{description}
+ )} + +
+ ); +} + +export type SettingSnippetLanguage = "shell" | "json" | "text"; + +/** The snippet half of a `SettingCommand`, for places with their own title, like a banner. */ +export function SettingSnippet({ + className, + language, + snippet, +}: { + className?: string; + language: SettingSnippetLanguage; + snippet: string; +}) { + const prompt = language === "shell"; + + return ( +
+
+ + {prompt && ( + + $ + + )} + {snippet} + +
+ +
+ ); +} + type SettingValueAction = { icon: IconButtonProps["icon"]; onClick: () => void; diff --git a/apps/yaak-client/hooks/usePluginInfo.ts b/apps/yaak-client/hooks/usePluginInfo.ts index 4a7f345e6..68effafd8 100644 --- a/apps/yaak-client/hooks/usePluginInfo.ts +++ b/apps/yaak-client/hooks/usePluginInfo.ts @@ -1,4 +1,4 @@ -import { useQuery } from "@tanstack/react-query"; +import { useQueries, useQuery } from "@tanstack/react-query"; import type { Plugin } from "@yaakapp-internal/models"; import { pluginsAtom } from "@yaakapp-internal/models"; import type { PluginMetadata } from "@yaakapp-internal/plugins"; @@ -24,6 +24,22 @@ export function usePluginInfo(id: string | null) { }); } +/** Every plugin with its metadata, once loaded; the ones still loading are left out. */ +export function usePluginInfos() { + const plugins = useAtomValue(pluginsAtom); + return useQueries({ + queries: plugins.map((plugin) => ({ + queryKey: pluginInfoKey(plugin.id, plugin), + queryFn: () => rpc("cmd_plugin_info", { id: plugin.id }), + })), + combine: (results) => + results.flatMap((result, i) => { + const plugin = plugins[i]; + return result.data == null || plugin == null ? [] : [{ plugin, info: result.data }]; + }), + }); +} + export function invalidateAllPluginInfo() { queryClient.invalidateQueries({ queryKey: ["plugin_info"] }).catch(console.error); } diff --git a/apps/yaak-client/hooks/useUninstallPlugin.tsx b/apps/yaak-client/hooks/useUninstallPlugin.tsx new file mode 100644 index 000000000..faa6f5163 --- /dev/null +++ b/apps/yaak-client/hooks/useUninstallPlugin.tsx @@ -0,0 +1,31 @@ +import { useMutation } from "@tanstack/react-query"; +import { uninstallPlugin } from "@yaakapp-internal/plugins"; +import { InlineCode } from "@yaakapp-internal/ui"; +import { showConfirmDelete } from "../lib/confirm"; +import { minPromiseMillis } from "../lib/minPromiseMillis"; + +/** Confirms, then uninstalls. Null until there is a plugin to uninstall. */ +export function usePromptUninstallPlugin(pluginId: string | null, name: string) { + const mut = useMutation({ + mutationKey: ["uninstall_plugin", pluginId], + mutationFn: async () => { + if (pluginId == null) return; + + const confirmed = await showConfirmDelete({ + id: `uninstall-plugin-${pluginId}`, + title: "Uninstall Plugin", + confirmText: "Uninstall", + description: ( + <> + Permanently uninstall {name}? + + ), + }); + if (confirmed) { + await minPromiseMillis(uninstallPlugin(pluginId), 700); + } + }, + }); + + return pluginId == null ? null : mut; +} diff --git a/apps/yaak-client/lib/agentSetup.test.ts b/apps/yaak-client/lib/agentSetup.test.ts index 847d88a2f..c7ea135f7 100644 --- a/apps/yaak-client/lib/agentSetup.test.ts +++ b/apps/yaak-client/lib/agentSetup.test.ts @@ -1,15 +1,20 @@ import { describe, expect, test } from "vite-plus/test"; -import { AGENT_CLIENTS, appSetup, cliSetup } from "./agentSetup"; - -const URL = "http://127.0.0.1:64343/mcp"; -const TOKEN = "abc123"; +import { AGENT_CLIENTS, cliSetup, skillInstallCommand } from "./agentSetup"; describe("cliSetup", () => { test("uses each client's own add command", () => { - expect(cliSetup("claude_code").snippet).toBe("claude mcp add yaak -- yaak mcp"); + expect(cliSetup("claude_code").snippet).toBe("claude mcp add -s user yaak -- yaak mcp"); expect(cliSetup("codex").snippet).toBe("codex mcp add yaak -- yaak mcp"); }); + test("names a file only when the snippet goes in one", () => { + expect(cliSetup("claude_code").where).toBeNull(); + expect(cliSetup("codex").where).toBeNull(); + expect(cliSetup("cursor").where).toBe("Add to ~/.cursor/mcp.json."); + expect(cliSetup("vscode").where).toContain("mcp.json"); + expect(cliSetup("other").where).not.toBeNull(); + }); + test("writes the config shape each client reads", () => { expect(JSON.parse(cliSetup("cursor").snippet)).toEqual({ mcpServers: { yaak: { command: "yaak", args: ["mcp"] } }, @@ -21,42 +26,27 @@ describe("cliSetup", () => { mcpServers: { yaak: { command: "yaak", args: ["mcp"] } }, }); }); -}); - -describe("appSetup", () => { - test("passes the token as a bearer header", () => { - expect(appSetup("claude_code", URL, TOKEN).snippet).toBe( - `claude mcp add --transport http yaak ${URL} --header "Authorization: Bearer ${TOKEN}"`, - ); - expect(appSetup("codex", URL, TOKEN).snippet).toBe( - `[mcp_servers.yaak]\nurl = "${URL}"\nhttp_headers = { "Authorization" = "Bearer ${TOKEN}" }`, - ); - expect(JSON.parse(appSetup("cursor", URL, TOKEN).snippet)).toEqual({ - mcpServers: { yaak: { url: URL, headers: { Authorization: `Bearer ${TOKEN}` } } }, - }); - expect(JSON.parse(appSetup("vscode", URL, TOKEN).snippet)).toEqual({ - servers: { yaak: { type: "http", url: URL, headers: { Authorization: `Bearer ${TOKEN}` } } }, - }); - expect(JSON.parse(appSetup("other", URL, TOKEN).snippet)).toEqual({ - mcpServers: { - yaak: { - command: "npx", - args: ["-y", "mcp-remote", URL, "--header", `Authorization: Bearer ${TOKEN}`], - }, - }, - }); - }); test("keeps argument lists on one line", () => { - expect(appSetup("other", URL, TOKEN).snippet).toContain( - `"args": ["-y", "mcp-remote", "${URL}", "--header", "Authorization: Bearer ${TOKEN}"]`, - ); + expect(cliSetup("cursor").snippet).toContain(`"args": ["mcp"]`); }); test("covers every listed client", () => { for (const { value } of AGENT_CLIENTS) { expect(cliSetup(value).snippet).not.toBe(""); - expect(appSetup(value, URL, TOKEN).snippet).toContain(TOKEN); } }); }); + +describe("skillInstallCommand", () => { + test("targets the agents the installer knows by name", () => { + expect(skillInstallCommand("claude_code")).toBe("yaak agent install --agent claude-code"); + expect(skillInstallCommand("codex")).toBe("yaak agent install --agent codex"); + expect(skillInstallCommand("cursor")).toBe("yaak agent install --agent cursor"); + }); + + test("installs everywhere for agents it cannot target", () => { + expect(skillInstallCommand("vscode")).toBe("yaak agent install"); + expect(skillInstallCommand("other")).toBe("yaak agent install"); + }); +}); diff --git a/apps/yaak-client/lib/agentSetup.ts b/apps/yaak-client/lib/agentSetup.ts index fd5e489e2..fe969f727 100644 --- a/apps/yaak-client/lib/agentSetup.ts +++ b/apps/yaak-client/lib/agentSetup.ts @@ -1,4 +1,6 @@ -export type AgentClient = "claude_code" | "codex" | "cursor" | "vscode" | "other"; +import type { AgentClient } from "@yaakapp-internal/rpc-schema"; + +export type { AgentClient }; export const AGENT_CLIENTS: { label: string; value: AgentClient }[] = [ { label: "Claude Code", value: "claude_code" }, @@ -9,21 +11,34 @@ export const AGENT_CLIENTS: { label: string; value: AgentClient }[] = [ ]; export interface AgentSetup { - /** Where the snippet goes, as a sentence */ - where: string; + /** The file the snippet goes in, as a sentence, when it is a file rather than a command */ + where: string | null; snippet: string; language: "shell" | "json" | "text"; } -const RUN_IN_TERMINAL = "Run in a terminal."; +/** `yaak agent install`, targeted at `client` when the installer knows it by name. */ +export function skillInstallCommand(client: AgentClient): string { + switch (client) { + case "claude_code": + return "yaak agent install --agent claude-code"; + case "codex": + return "yaak agent install --agent codex"; + case "cursor": + return "yaak agent install --agent cursor"; + case "vscode": + case "other": + return "yaak agent install"; + } +} /** Setup for `yaak mcp`, which the client launches over stdio. */ export function cliSetup(client: AgentClient): AgentSetup { switch (client) { case "claude_code": - return { where: RUN_IN_TERMINAL, snippet: "claude mcp add yaak -- yaak mcp", language: "shell" }; + return { where: null, snippet: "claude mcp add -s user yaak -- yaak mcp", language: "shell" }; case "codex": - return { where: RUN_IN_TERMINAL, snippet: "codex mcp add yaak -- yaak mcp", language: "shell" }; + return { where: null, snippet: "codex mcp add yaak -- yaak mcp", language: "shell" }; case "cursor": return { where: "Add to ~/.cursor/mcp.json.", @@ -45,56 +60,6 @@ export function cliSetup(client: AgentClient): AgentSetup { } } -/** Setup for the app's MCP server at `url`, which needs `token` as a bearer token. */ -export function appSetup(client: AgentClient, url: string, token: string): AgentSetup { - const authorization = `Bearer ${token}`; - switch (client) { - case "claude_code": - return { - where: RUN_IN_TERMINAL, - snippet: `claude mcp add --transport http yaak ${url} --header "Authorization: ${authorization}"`, - language: "shell", - }; - case "codex": - return { - where: "Add to ~/.codex/config.toml.", - snippet: [ - "[mcp_servers.yaak]", - `url = ${JSON.stringify(url)}`, - `http_headers = { "Authorization" = ${JSON.stringify(authorization)} }`, - ].join("\n"), - language: "text", - }; - case "cursor": - return { - where: "Add to ~/.cursor/mcp.json.", - snippet: json({ mcpServers: { yaak: { url, headers: { Authorization: authorization } } } }), - language: "json", - }; - case "vscode": - return { - where: "Add to your user mcp.json (MCP: Open User Configuration).", - snippet: json({ - servers: { yaak: { type: "http", url, headers: { Authorization: authorization } } }, - }), - language: "json", - }; - case "other": - return { - where: "For clients that read an mcpServers config, through the mcp-remote bridge.", - snippet: json({ - mcpServers: { - yaak: { - command: "npx", - args: ["-y", "mcp-remote", url, "--header", `Authorization: ${authorization}`], - }, - }, - }), - language: "json", - }; - } -} - /** Pretty JSON with arrays of plain values kept on one line. */ function json(value: unknown): string { return JSON.stringify(value, null, 2).replace( diff --git a/crates-cli/yaak-cli/src/cli.rs b/crates-cli/yaak-cli/src/cli.rs index b27b98be9..c52ff72bf 100644 --- a/crates-cli/yaak-cli/src/cli.rs +++ b/crates-cli/yaak-cli/src/cli.rs @@ -93,8 +93,23 @@ pub enum Commands { /// Response commands Response(ResponseArgs), - /// Serve Yaak's MCP tools over stdio, for AI agents like Claude Code - Mcp, + /// Serve Yaak's MCP tools to AI agents like Claude Code, over stdio or with --http + Mcp(McpArgs), +} + +#[derive(Args)] +pub struct McpArgs { + /// Serve over HTTP on 127.0.0.1 instead of stdio, for agents that cannot run this command + #[arg(long)] + pub http: bool, + + /// Port to listen on with --http + #[arg(long, default_value_t = yaak_mcp::http::DEFAULT_PORT, requires = "http")] + pub port: u16, + + /// Bearer token clients must send with --http; generated and printed when omitted + #[arg(long, requires = "http", value_name = "TOKEN")] + pub token: Option, } #[derive(Args)] diff --git a/crates-cli/yaak-cli/src/commands/mcp.rs b/crates-cli/yaak-cli/src/commands/mcp.rs index b2361b5f6..aef666b6e 100644 --- a/crates-cli/yaak-cli/src/commands/mcp.rs +++ b/crates-cli/yaak-cli/src/commands/mcp.rs @@ -1,5 +1,8 @@ +use crate::cli::McpArgs; use crate::context::{CliContext, CliExecutionContext}; use crate::plugin_events::SendContexts; +use rand::Rng; +use std::net::{Ipv4Addr, SocketAddr}; use std::path::PathBuf; use std::sync::Arc; use yaak::send::{SendHttpRequestWithPluginsParams, send_http_request_with_plugins}; @@ -13,7 +16,27 @@ use yaak_models::util::UpdateSource; use yaak_plugins::events::{PluginContext, ShowToastRequest}; use yaak_plugins::manager::PluginManager; -pub async fn run(ctx: &CliContext, environment: Option<&str>, cookie_jar_id: Option<&str>) -> i32 { +enum Transport { + Stdio, + Http { port: u16, token: Option }, +} + +impl From for Transport { + fn from(args: McpArgs) -> Self { + if args.http { + Transport::Http { port: args.port, token: args.token } + } else { + Transport::Stdio + } + } +} + +pub async fn run( + ctx: &CliContext, + args: McpArgs, + environment: Option<&str>, + cookie_jar_id: Option<&str>, +) -> i32 { let host = CliMcpHost { query_manager: ctx.query_manager().clone(), blob_manager: ctx.blob_manager().clone(), @@ -25,7 +48,11 @@ pub async fn run(ctx: &CliContext, environment: Option<&str>, cookie_jar_id: Opt environment_id: environment.map(str::to_string), cookie_jar_id: cookie_jar_id.map(str::to_string), }; - match yaak_mcp::serve_stdio(host).await { + let result = match Transport::from(args) { + Transport::Stdio => yaak_mcp::serve_stdio(host).await, + Transport::Http { port, token } => serve_http(host, port, token).await, + }; + match result { Ok(()) => 0, Err(error) => { eprintln!("Error: {error}"); @@ -34,6 +61,24 @@ pub async fn run(ctx: &CliContext, environment: Option<&str>, cookie_jar_id: Opt } } +async fn serve_http(host: CliMcpHost, port: u16, token: Option) -> Result<(), String> { + let token = token.unwrap_or_else(generate_token); + let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port)); + let server = yaak_mcp::http::serve(Arc::new(host), addr, token.clone()) + .await + .map_err(|e| format!("Failed to start MCP server on {addr}: {e}"))?; + eprintln!("Yaak MCP server listening on http://{}{}", server.addr, yaak_mcp::http::PATH); + eprintln!("Token: {token}"); + eprintln!("Clients must send it as \"Authorization: Bearer \". Press Ctrl+C to stop."); + tokio::signal::ctrl_c().await.map_err(|e| format!("Failed to wait for Ctrl+C: {e}"))?; + server.stop().await; + Ok(()) +} + +fn generate_token() -> String { + hex::encode(rand::thread_rng().r#gen::<[u8; 32]>()) +} + /// Every workspace in the database is "open", and the global `--environment` /// and `--cookie-jar` flags stand in for a window's selection. struct CliMcpHost { diff --git a/crates-cli/yaak-cli/src/main.rs b/crates-cli/yaak-cli/src/main.rs index d911c1409..f18edf39b 100644 --- a/crates-cli/yaak-cli/src/main.rs +++ b/crates-cli/yaak-cli/src/main.rs @@ -184,7 +184,7 @@ async fn main() { context.shutdown().await; exit_code } - Commands::Mcp => { + Commands::Mcp(args) => { let mut context = CliContext::new(data_dir.clone(), app_id); context .init_plugins(CliExecutionContext { @@ -194,7 +194,8 @@ async fn main() { }) .await; let exit_code = - commands::mcp::run(&context, environment.as_deref(), cookie_jar.as_deref()).await; + commands::mcp::run(&context, args, environment.as_deref(), cookie_jar.as_deref()) + .await; context.shutdown().await; exit_code } diff --git a/crates-cli/yaak-cli/tests/mcp_command.rs b/crates-cli/yaak-cli/tests/mcp_command.rs index b9d7a0e86..7f892e08d 100644 --- a/crates-cli/yaak-cli/tests/mcp_command.rs +++ b/crates-cli/yaak-cli/tests/mcp_command.rs @@ -222,3 +222,129 @@ async fn mcp_send_settings_reach_template_functions() { client.cancel().await.unwrap(); assert!(child.wait().await.unwrap().success()); } + +/// Spawns `yaak mcp --http` with `args` and returns the child, the URL it +/// printed, and the token it printed or was given. +async fn spawn_http(data_dir: &std::path::Path, args: &[&str]) -> (tokio::process::Child, String, String) { + use tokio::io::AsyncBufReadExt; + + let mut child = Command::new(env!("CARGO_BIN_EXE_yaak")) + .arg("--data-dir") + .arg(data_dir) + .args(["mcp", "--http", "--port", "0"]) + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let mut stderr = tokio::io::BufReader::new(child.stderr.take().unwrap()).lines(); + let mut url = None; + let mut token = None; + while url.is_none() || token.is_none() { + let line = stderr.next_line().await.unwrap().expect("server exited before announcing"); + if let Some(rest) = line.strip_prefix("Yaak MCP server listening on ") { + url = Some(rest.to_string()); + } else if let Some(rest) = line.strip_prefix("Token: ") { + token = Some(rest.to_string()); + } + } + (child, url.unwrap(), token.unwrap()) +} + +/// Posts one JSON-RPC message, with the session id when there is one, and +/// returns the response and its body parsed out of either JSON or SSE. +async fn post( + client: &reqwest::Client, + url: &str, + auth: Option<&str>, + session: Option<&str>, + body: Value, +) -> (reqwest::StatusCode, reqwest::header::HeaderMap, Option) { + let mut request = client + .post(url) + .header("Content-Type", "application/json") + .header("Accept", "application/json, text/event-stream") + .body(body.to_string()); + if let Some(auth) = auth { + request = request.header("Authorization", auth); + } + if let Some(session) = session { + request = request.header("Mcp-Session-Id", session); + } + let response = request.send().await.unwrap(); + let status = response.status(); + let headers = response.headers().clone(); + let text = response.text().await.unwrap(); + let message = text + .lines() + .filter_map(|l| l.strip_prefix("data:")) + .last() + .map(str::trim) + .unwrap_or(text.trim()); + (status, headers, serde_json::from_str(message).ok()) +} + +#[tokio::test] +async fn mcp_http_requires_the_token() { + let temp_dir = TempDir::new().expect("Failed to create temp dir"); + let data_dir = temp_dir.path(); + seed_workspace(data_dir, "wk_test"); + let (mut child, url, token) = spawn_http(data_dir, &["--token", "s3cret"]).await; + assert_eq!(token, "s3cret"); + assert!(url.starts_with("http://127.0.0.1:"), "{url}"); + assert!(url.ends_with("/mcp"), "{url}"); + let client = reqwest::Client::new(); + let initialize = json!({ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": { "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": { "name": "test", "version": "1.0" } } + }); + + for auth in [None, Some("Bearer wrong")] { + let (status, headers, _) = post(&client, &url, auth, None, initialize.clone()).await; + assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED, "{auth:?}"); + assert_eq!(headers["www-authenticate"], "Bearer"); + } + + let auth = Some("Bearer s3cret"); + let (status, headers, body) = post(&client, &url, auth, None, initialize).await; + assert_eq!(status, reqwest::StatusCode::OK); + let session = headers["mcp-session-id"].to_str().unwrap().to_string(); + assert_eq!(body.unwrap()["result"]["serverInfo"]["name"], "yaak-mcp-server"); + + let initialized = json!({ "jsonrpc": "2.0", "method": "notifications/initialized" }); + let (status, _, _) = post(&client, &url, auth, Some(&session), initialized).await; + assert_eq!(status, reqwest::StatusCode::ACCEPTED); + + let list = json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {} }); + let (status, _, body) = post(&client, &url, auth, Some(&session), list).await; + assert_eq!(status, reqwest::StatusCode::OK); + let tools = body.unwrap()["result"]["tools"].as_array().unwrap().len(); + assert_eq!(tools, 15); + + child.kill().await.unwrap(); +} + +#[tokio::test] +async fn mcp_http_generates_a_token() { + let temp_dir = TempDir::new().expect("Failed to create temp dir"); + let data_dir = temp_dir.path(); + seed_workspace(data_dir, "wk_test"); + let (mut child, url, token) = spawn_http(data_dir, &[]).await; + assert_eq!(token.len(), 64, "{token}"); + assert!(token.chars().all(|c| c.is_ascii_hexdigit()), "{token}"); + + let client = reqwest::Client::new(); + let initialize = json!({ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": { "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": { "name": "test", "version": "1.0" } } + }); + let (status, _, _) = post(&client, &url, None, None, initialize.clone()).await; + assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED); + let (status, _, _) = + post(&client, &url, Some(&format!("Bearer {token}")), None, initialize).await; + assert_eq!(status, reqwest::StatusCode::OK); + + child.kill().await.unwrap(); +} diff --git a/crates-tauri/yaak-app-client/src/lib.rs b/crates-tauri/yaak-app-client/src/lib.rs index e53668207..6619569de 100644 --- a/crates-tauri/yaak-app-client/src/lib.rs +++ b/crates-tauri/yaak-app-client/src/lib.rs @@ -62,7 +62,6 @@ mod grpc; mod history; mod http_request; mod import; -mod mcp_ext; mod models_ext; mod notifications; mod plugin_events; @@ -1362,7 +1361,6 @@ pub fn run() { app.app_handle().set_native_titlebar(settings.use_native_titlebar); monitor_plugin_events(&app.app_handle().clone()); - mcp_ext::init(app.app_handle()); Ok(()) }) diff --git a/crates-tauri/yaak-app-client/src/mcp_ext.rs b/crates-tauri/yaak-app-client/src/mcp_ext.rs deleted file mode 100644 index 6e7ed28ed..000000000 --- a/crates-tauri/yaak-app-client/src/mcp_ext.rs +++ /dev/null @@ -1,192 +0,0 @@ -//! The built-in MCP server: `yaak_mcp`'s tools on 127.0.0.1:64343, served -//! while the `mcpServerEnabled` setting is on, behind a bearer token kept in -//! key_values. - -use crate::models_ext::QueryManagerExt; -use crate::plugin_events::send_http_request_in_window; -use crate::{environment_from_window, workspace_from_window}; -use log::{error, info}; -use rand::Rng; -use std::net::{Ipv4Addr, SocketAddr}; -use std::sync::Arc; -use tauri::{AppHandle, Emitter, Manager, Runtime, WebviewWindow}; -use tokio::sync::Mutex; -use yaak_mcp::http::{DEFAULT_PORT, HttpServer}; -use yaak_mcp::{HostResult, McpHost, WorkspaceInfo}; -use yaak_models::models::{Folder, HttpRequest, HttpResponse}; -use yaak_models::util::UpdateSource; -use yaak_plugins::events::{Color, PluginContext, ShowToastRequest}; - -pub(crate) const TOKEN_NAMESPACE: &str = "no_sync"; -pub(crate) const TOKEN_KEY: &str = "mcp_server_token"; - -#[derive(Default)] -struct McpServerState(Mutex>); - -pub(crate) fn init(app_handle: &AppHandle) { - app_handle.manage(McpServerState::default()); - sync(app_handle); -} - -/// Start or stop the server to match the setting. -pub(crate) fn sync(app_handle: &AppHandle) { - let app_handle = app_handle.clone(); - tauri::async_runtime::spawn(async move { - let Some(state) = app_handle.try_state::() else { - return; - }; - let mut server = state.0.lock().await; - let enabled = app_handle.db().get_settings().mcp_server_enabled; - match (enabled, server.is_some()) { - (true, false) => match start(&app_handle).await { - Ok(s) => { - info!("MCP server listening on http://{}{}", s.addr, yaak_mcp::http::PATH); - *server = Some(s); - } - Err(e) => { - error!("Failed to start MCP server: {e}"); - let _ = app_handle.emit( - "show_toast", - ShowToastRequest { - message: format!( - "Failed to start the MCP server on port {DEFAULT_PORT}: {e}" - ), - color: Some(Color::Danger), - timeout: Some(10000), - ..Default::default() - }, - ); - } - }, - (false, true) => { - if let Some(s) = server.take() { - s.stop().await; - info!("MCP server stopped"); - } - } - (true, true) | (false, false) => {} - } - }); -} - -async fn start(app_handle: &AppHandle) -> std::io::Result { - let host = Arc::new(AppMcpHost { app_handle: app_handle.clone() }); - let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, DEFAULT_PORT)); - yaak_mcp::http::serve(host, addr, token(app_handle)).await -} - -/// The token, generated the first time the server starts. -fn token(app_handle: &AppHandle) -> String { - let existing = app_handle.db().get_key_value_str(TOKEN_NAMESPACE, TOKEN_KEY, ""); - if !existing.is_empty() { - return existing; - } - let mut rng = rand::rng(); - let token: String = (0..32).map(|_| format!("{:02x}", rng.random::())).collect(); - if let Err(e) = app_handle.with_tx(|tx| { - tx.set_key_value_str(TOKEN_NAMESPACE, TOKEN_KEY, &token, &UpdateSource::Background); - Ok(()) - }) { - error!("Failed to save MCP server token: {e}"); - } - token -} - -struct AppMcpHost { - app_handle: AppHandle, -} - -impl AppMcpHost { - fn window_for_workspace(&self, workspace_id: &str) -> Option> { - self.app_handle - .webview_windows() - .into_values() - .find(|w| workspace_from_window(w).is_some_and(|ws| ws.id == workspace_id)) - } -} - -impl McpHost for AppMcpHost { - fn list_workspaces(&self) -> HostResult> { - let mut workspaces: Vec = Vec::new(); - for window in self.app_handle.webview_windows().values() { - if let Some(w) = workspace_from_window(window) - && !workspaces.iter().any(|existing| existing.id == w.id) - { - workspaces.push(WorkspaceInfo { id: w.id, name: w.name }); - } - } - Ok(workspaces) - } - - fn active_environment_id(&self, workspace_id: &str) -> HostResult> { - Ok(self - .window_for_workspace(workspace_id) - .and_then(|w| environment_from_window(&w)) - .map(|e| e.id)) - } - - fn list_http_requests(&self, workspace_id: &str) -> HostResult> { - self.app_handle.db().list_http_requests(workspace_id).map_err(|e| e.to_string()) - } - - fn get_http_request(&self, id: &str) -> HostResult> { - Ok(self.app_handle.db().get_http_request(id).ok()) - } - - fn upsert_http_request(&self, request: &HttpRequest) -> HostResult { - self.app_handle - .with_tx(|tx| tx.upsert_http_request(request, &UpdateSource::Plugin)) - .map_err(|e| format!("Failed to upsert HTTP request: {e}")) - } - - fn delete_http_request(&self, id: &str) -> HostResult { - self.app_handle - .with_tx(|tx| tx.delete_http_request_by_id(id, &UpdateSource::Plugin)) - .map_err(|e| format!("Failed to delete HTTP request: {e}")) - } - - fn list_folders(&self, workspace_id: &str) -> HostResult> { - self.app_handle.db().list_folders(workspace_id).map_err(|e| e.to_string()) - } - - fn upsert_folder(&self, folder: &Folder) -> HostResult { - self.app_handle - .with_tx(|tx| tx.upsert_folder(folder, &UpdateSource::Plugin)) - .map_err(|e| format!("Failed to upsert folder: {e}")) - } - - fn delete_folder(&self, id: &str) -> HostResult { - self.app_handle - .with_tx(|tx| tx.delete_folder_by_id(id, &UpdateSource::Plugin)) - .map_err(|e| format!("Failed to delete folder: {e}")) - } - - async fn send_http_request( - &self, - workspace_id: &str, - request: HttpRequest, - environment_id: Option, - ) -> HostResult { - let window = self - .window_for_workspace(workspace_id) - .ok_or_else(|| format!("No window is open for workspace {workspace_id}"))?; - let plugin_context = PluginContext { - label: Some(window.label().to_string()), - workspace_id: Some(workspace_id.to_string()), - ..PluginContext::new_empty() - }; - let sent = send_http_request_in_window( - &window, - request, - environment_id.as_deref(), - &plugin_context, - ) - .await - .map_err(|e| e.to_string())?; - Ok(sent.response) - } - - fn show_toast(&self, toast: ShowToastRequest) -> HostResult<()> { - self.app_handle.emit("show_toast", toast).map_err(|e| e.to_string()) - } -} diff --git a/crates-tauri/yaak-app-client/src/models_ext.rs b/crates-tauri/yaak-app-client/src/models_ext.rs index f0a149a60..5243c26a9 100644 --- a/crates-tauri/yaak-app-client/src/models_ext.rs +++ b/crates-tauri/yaak-app-client/src/models_ext.rs @@ -12,7 +12,6 @@ use tauri_plugin_dialog::{DialogExt, MessageDialogKind}; use yaak_models::blob_manager::BlobManager; use yaak_models::client_db::{ClientDb, WriteDb}; use yaak_models::error::Result; -use yaak_models::models::AnyModel; use yaak_models::query_manager::QueryManager; use yaak_models::util::{ModelPayload, UpdateSource}; @@ -175,20 +174,15 @@ pub fn init() -> TauriPlugin { std::thread::spawn(move || { while let Ok(payload) = rx.recv() { let mut batch: Vec = Vec::new(); - let mut settings_changed = matches!(payload.model, AnyModel::Settings(_)); if matches!(payload.update_source, UpdateSource::Window { .. }) { batch.push(payload); } // Coalesce any writes already queued into the same emit while let Ok(next) = rx.try_recv() { - settings_changed |= matches!(next.model, AnyModel::Settings(_)); if matches!(next.update_source, UpdateSource::Window { .. }) { batch.push(next); } } - if settings_changed { - crate::mcp_ext::sync(&app_handle_local); - } if batch.is_empty() { continue; } diff --git a/crates-tauri/yaak-app-client/src/rpc_ext.rs b/crates-tauri/yaak-app-client/src/rpc_ext.rs index 4a35ea1fa..d783c74d3 100644 --- a/crates-tauri/yaak-app-client/src/rpc_ext.rs +++ b/crates-tauri/yaak-app-client/src/rpc_ext.rs @@ -391,6 +391,14 @@ async fn cmd_metadata(ctx: ClientCtx, _req: CmdMetadataReq) -> Re Ok(crate::cmd_metadata(ctx.window.app_handle().clone()).await?) } +async fn cmd_agent_setup_status( + ctx: ClientCtx, + req: CmdAgentSetupStatusReq, +) -> Result { + let home = ctx.window.app_handle().path().home_dir()?; + Ok(yaak_commands::agents::agent_setup_status(&home, req.agent)) +} + async fn cmd_template_tokens_to_string( ctx: ClientCtx, req: CmdTemplateTokensToStringReq, diff --git a/crates/common/yaak-rpc-schema/bindings/gen_rpc.ts b/crates/common/yaak-rpc-schema/bindings/gen_rpc.ts index 0345336d2..0d4538b43 100644 --- a/crates/common/yaak-rpc-schema/bindings/gen_rpc.ts +++ b/crates/common/yaak-rpc-schema/bindings/gen_rpc.ts @@ -10,11 +10,24 @@ import type { BatchUpsertResult, ImportDestination, ImportPlan } from "./gen_uti import type { Tokens } from "./parser"; import type { ServerSentEvent } from "./sse"; +/** + * A coding agent the Agents settings pane can set up. + */ +export type AgentClient = "claude_code" | "codex" | "cursor" | "vscode" | "other"; + +/** + * Which setup steps an agent already has done on this machine. `None` means + * the pane cannot tell for that agent. + */ +export type AgentSetupStatus = { mcpServer: boolean | null, skill: boolean | null, }; + /** * What the frontend learns about the host it is talking to. */ export type AppMetaData = { isDev: boolean, version: string, cliVersion: string | null, name: string, appDataDir: string, appLogDir: string, vendoredPluginDir: string, defaultProjectDir: string, featureUpdater: boolean, featureLicense: boolean, }; +export type CmdAgentSetupStatusReq = { agent: AgentClient, }; + export type CmdCallFolderActionReq = { req: CallFolderActionRequest, }; export type CmdCallGrpcRequestActionReq = { req: CallGrpcRequestActionRequest, }; @@ -256,6 +269,6 @@ export type ModelsWebsocketEventsReq = { connectionId: string, }; export type ModelsWorkspaceModelsReq = { workspaceId: string | null, }; -export type RpcSchema = { cmd_metadata: [CmdMetadataReq, AppMetaData], cmd_template_tokens_to_string: [CmdTemplateTokensToStringReq, string], cmd_render_template: [CmdRenderTemplateReq, string], cmd_send_feedback: [CmdSendFeedbackReq, null], cmd_dismiss_notification: [CmdDismissNotificationReq, null], cmd_grpc_reflect: [CmdGrpcReflectReq, Array], cmd_grpc_go: [CmdGrpcGoReq, string], cmd_restart: [CmdRestartReq, null], cmd_send_ephemeral_request: [CmdSendEphemeralRequestReq, EphemeralHttpResponse], cmd_format_json: [CmdFormatJsonReq, string], cmd_format_graphql: [CmdFormatGraphqlReq, string], cmd_http_response_body: [CmdHttpResponseBodyReq, FilterResponse], cmd_http_response_body_path: [CmdHttpResponseBodyPathReq, string | null], cmd_http_request_body: [CmdHttpRequestBodyReq, Array | null], cmd_get_sse_events: [CmdGetSseEventsReq, Array], cmd_get_http_response_events: [CmdGetHttpResponseEventsReq, Array], cmd_import_data: [CmdImportDataReq, ImportPlan], cmd_commit_import: [CmdCommitImportReq, BatchUpsertResult], cmd_list_import_sources: [CmdListImportSourcesReq, Array], cmd_import_sources_for_origin: [CmdImportSourcesForOriginReq, Array], cmd_detect_import_source: [CmdDetectImportSourceReq, string], cmd_http_request_actions: [CmdHttpRequestActionsReq, Array], cmd_websocket_request_actions: [CmdWebsocketRequestActionsReq, Array], cmd_call_websocket_request_action: [CmdCallWebsocketRequestActionReq, null], cmd_workspace_actions: [CmdWorkspaceActionsReq, Array], cmd_call_workspace_action: [CmdCallWorkspaceActionReq, null], cmd_folder_actions: [CmdFolderActionsReq, Array], cmd_call_folder_action: [CmdCallFolderActionReq, null], cmd_grpc_request_actions: [CmdGrpcRequestActionsReq, Array], cmd_template_function_summaries: [CmdTemplateFunctionSummariesReq, Array], cmd_template_function_config: [CmdTemplateFunctionConfigReq, GetTemplateFunctionConfigResponse], cmd_get_http_authentication_summaries: [CmdGetHttpAuthenticationSummariesReq, Array], cmd_get_http_authentication_config: [CmdGetHttpAuthenticationConfigReq, GetHttpAuthenticationConfigResponse], cmd_call_http_request_action: [CmdCallHttpRequestActionReq, null], cmd_call_grpc_request_action: [CmdCallGrpcRequestActionReq, null], cmd_call_http_authentication_action: [CmdCallHttpAuthenticationActionReq, null], cmd_curl_to_request: [CmdCurlToRequestReq, HttpRequest], cmd_export_data: [CmdExportDataReq, string], cmd_create_example_workspace: [CmdCreateExampleWorkspaceReq, BatchUpsertResult], cmd_save_base64_to_binary: [CmdSaveBase64ToBinaryReq, null], cmd_save_response: [CmdSaveResponseReq, null], cmd_send_http_request: [CmdSendHttpRequestReq, HttpResponse], cmd_reload_plugins: [CmdReloadPluginsReq, Array<[string, string]>], cmd_plugin_info: [CmdPluginInfoReq, PluginMetadata], cmd_delete_all_grpc_connections: [CmdDeleteAllGrpcConnectionsReq, null], cmd_delete_send_history: [CmdDeleteSendHistoryReq, null], cmd_delete_all_http_responses: [CmdDeleteAllHttpResponsesReq, null], cmd_get_workspace_meta: [CmdGetWorkspaceMetaReq, WorkspaceMeta], cmd_new_child_window: [CmdNewChildWindowReq, null], cmd_new_main_window: [CmdNewMainWindowReq, null], cmd_check_for_updates: [CmdCheckForUpdatesReq, boolean], cmd_decrypt_template: [CmdDecryptTemplateReq, string], cmd_secure_template: [CmdSecureTemplateReq, string], cmd_get_themes: [CmdGetThemesReq, Array], cmd_enable_encryption: [CmdEnableEncryptionReq, null], cmd_reveal_workspace_key: [CmdRevealWorkspaceKeyReq, string], cmd_set_workspace_key: [CmdSetWorkspaceKeyReq, null], cmd_disable_encryption: [CmdDisableEncryptionReq, null], cmd_default_headers: [CmdDefaultHeadersReq, Array], models_upsert: [ModelsUpsertReq, string], models_delete: [ModelsDeleteReq, string], models_duplicate: [ModelsDuplicateReq, string], models_websocket_events: [ModelsWebsocketEventsReq, Array], models_grpc_events: [ModelsGrpcEventsReq, Array], models_get_settings: [ModelsGetSettingsReq, Settings], models_get_graphql_introspection: [ModelsGetGraphqlIntrospectionReq, GraphQlIntrospection | null], models_upsert_graphql_introspection: [ModelsUpsertGraphqlIntrospectionReq, GraphQlIntrospection], models_workspace_models: [ModelsWorkspaceModelsReq, string], cmd_git_checkout: [CmdGitCheckoutReq, string], cmd_git_branch: [CmdGitBranchReq, null], cmd_git_delete_branch: [CmdGitDeleteBranchReq, BranchDeleteResult], cmd_git_delete_remote_branch: [CmdGitDeleteRemoteBranchReq, null], cmd_git_merge_branch: [CmdGitMergeBranchReq, null], cmd_git_rename_branch: [CmdGitRenameBranchReq, null], cmd_git_status: [CmdGitStatusReq, GitStatusSummary], cmd_git_branch_info: [CmdGitBranchInfoReq, GitBranchInfo], cmd_git_worktree_status: [CmdGitWorktreeStatusReq, GitWorktreeStatus], cmd_git_log: [CmdGitLogReq, Array], cmd_git_log_for_file: [CmdGitLogForFileReq, Array], cmd_git_file_diff_for_commit: [CmdGitFileDiffForCommitReq, GitFileDiff], cmd_git_initialize: [CmdGitInitializeReq, null], cmd_git_clone: [CmdGitCloneReq, CloneResult], cmd_git_commit: [CmdGitCommitReq, null], cmd_git_fetch_all: [CmdGitFetchAllReq, null], cmd_git_push: [CmdGitPushReq, PushResult], cmd_git_pull: [CmdGitPullReq, PullResult], cmd_git_pull_force_reset: [CmdGitPullForceResetReq, PullResult], cmd_git_pull_merge: [CmdGitPullMergeReq, PullResult], cmd_git_add: [CmdGitAddReq, null], cmd_git_unstage: [CmdGitUnstageReq, null], cmd_git_reset_changes: [CmdGitResetChangesReq, null], cmd_git_restore_files: [CmdGitRestoreFilesReq, null], cmd_git_restore_file_from_commit: [CmdGitRestoreFileFromCommitReq, null], cmd_git_add_credential: [CmdGitAddCredentialReq, null], cmd_git_remotes: [CmdGitRemotesReq, Array], cmd_git_add_remote: [CmdGitAddRemoteReq, GitRemote], cmd_git_rm_remote: [CmdGitRmRemoteReq, null], cmd_sync_calculate: [CmdSyncCalculateReq, Array], cmd_sync_calculate_fs: [CmdSyncCalculateFsReq, Array], cmd_sync_apply: [CmdSyncApplyReq, boolean], cmd_ws_delete_connections: [CmdWsDeleteConnectionsReq, null], cmd_ws_send: [CmdWsSendReq, WebsocketConnection], cmd_ws_close: [CmdWsCloseReq, WebsocketConnection], cmd_ws_connect: [CmdWsConnectReq, WebsocketConnection], cmd_plugins_search: [CmdPluginsSearchReq, PluginSearchResponse], cmd_plugins_install: [CmdPluginsInstallReq, null], cmd_plugins_install_from_directory: [CmdPluginsInstallFromDirectoryReq, Plugin], cmd_plugins_uninstall: [CmdPluginsUninstallReq, Plugin], cmd_plugin_init_errors: [CmdPluginInitErrorsReq, Array<[string, string]>], cmd_plugins_updates: [CmdPluginsUpdatesReq, PluginUpdatesResponse], cmd_plugins_update_all: [CmdPluginsUpdateAllReq, Array], cmd_git_watch_worktree_status: [CmdGitWatchWorktreeStatusReq, GitWatchResult], cmd_sync_watch: [CmdSyncWatchReq, WatchResult], }; +export type RpcSchema = { cmd_metadata: [CmdMetadataReq, AppMetaData], cmd_agent_setup_status: [CmdAgentSetupStatusReq, AgentSetupStatus], cmd_template_tokens_to_string: [CmdTemplateTokensToStringReq, string], cmd_render_template: [CmdRenderTemplateReq, string], cmd_send_feedback: [CmdSendFeedbackReq, null], cmd_dismiss_notification: [CmdDismissNotificationReq, null], cmd_grpc_reflect: [CmdGrpcReflectReq, Array], cmd_grpc_go: [CmdGrpcGoReq, string], cmd_restart: [CmdRestartReq, null], cmd_send_ephemeral_request: [CmdSendEphemeralRequestReq, EphemeralHttpResponse], cmd_format_json: [CmdFormatJsonReq, string], cmd_format_graphql: [CmdFormatGraphqlReq, string], cmd_http_response_body: [CmdHttpResponseBodyReq, FilterResponse], cmd_http_response_body_path: [CmdHttpResponseBodyPathReq, string | null], cmd_http_request_body: [CmdHttpRequestBodyReq, Array | null], cmd_get_sse_events: [CmdGetSseEventsReq, Array], cmd_get_http_response_events: [CmdGetHttpResponseEventsReq, Array], cmd_import_data: [CmdImportDataReq, ImportPlan], cmd_commit_import: [CmdCommitImportReq, BatchUpsertResult], cmd_list_import_sources: [CmdListImportSourcesReq, Array], cmd_import_sources_for_origin: [CmdImportSourcesForOriginReq, Array], cmd_detect_import_source: [CmdDetectImportSourceReq, string], cmd_http_request_actions: [CmdHttpRequestActionsReq, Array], cmd_websocket_request_actions: [CmdWebsocketRequestActionsReq, Array], cmd_call_websocket_request_action: [CmdCallWebsocketRequestActionReq, null], cmd_workspace_actions: [CmdWorkspaceActionsReq, Array], cmd_call_workspace_action: [CmdCallWorkspaceActionReq, null], cmd_folder_actions: [CmdFolderActionsReq, Array], cmd_call_folder_action: [CmdCallFolderActionReq, null], cmd_grpc_request_actions: [CmdGrpcRequestActionsReq, Array], cmd_template_function_summaries: [CmdTemplateFunctionSummariesReq, Array], cmd_template_function_config: [CmdTemplateFunctionConfigReq, GetTemplateFunctionConfigResponse], cmd_get_http_authentication_summaries: [CmdGetHttpAuthenticationSummariesReq, Array], cmd_get_http_authentication_config: [CmdGetHttpAuthenticationConfigReq, GetHttpAuthenticationConfigResponse], cmd_call_http_request_action: [CmdCallHttpRequestActionReq, null], cmd_call_grpc_request_action: [CmdCallGrpcRequestActionReq, null], cmd_call_http_authentication_action: [CmdCallHttpAuthenticationActionReq, null], cmd_curl_to_request: [CmdCurlToRequestReq, HttpRequest], cmd_export_data: [CmdExportDataReq, string], cmd_create_example_workspace: [CmdCreateExampleWorkspaceReq, BatchUpsertResult], cmd_save_base64_to_binary: [CmdSaveBase64ToBinaryReq, null], cmd_save_response: [CmdSaveResponseReq, null], cmd_send_http_request: [CmdSendHttpRequestReq, HttpResponse], cmd_reload_plugins: [CmdReloadPluginsReq, Array<[string, string]>], cmd_plugin_info: [CmdPluginInfoReq, PluginMetadata], cmd_delete_all_grpc_connections: [CmdDeleteAllGrpcConnectionsReq, null], cmd_delete_send_history: [CmdDeleteSendHistoryReq, null], cmd_delete_all_http_responses: [CmdDeleteAllHttpResponsesReq, null], cmd_get_workspace_meta: [CmdGetWorkspaceMetaReq, WorkspaceMeta], cmd_new_child_window: [CmdNewChildWindowReq, null], cmd_new_main_window: [CmdNewMainWindowReq, null], cmd_check_for_updates: [CmdCheckForUpdatesReq, boolean], cmd_decrypt_template: [CmdDecryptTemplateReq, string], cmd_secure_template: [CmdSecureTemplateReq, string], cmd_get_themes: [CmdGetThemesReq, Array], cmd_enable_encryption: [CmdEnableEncryptionReq, null], cmd_reveal_workspace_key: [CmdRevealWorkspaceKeyReq, string], cmd_set_workspace_key: [CmdSetWorkspaceKeyReq, null], cmd_disable_encryption: [CmdDisableEncryptionReq, null], cmd_default_headers: [CmdDefaultHeadersReq, Array], models_upsert: [ModelsUpsertReq, string], models_delete: [ModelsDeleteReq, string], models_duplicate: [ModelsDuplicateReq, string], models_websocket_events: [ModelsWebsocketEventsReq, Array], models_grpc_events: [ModelsGrpcEventsReq, Array], models_get_settings: [ModelsGetSettingsReq, Settings], models_get_graphql_introspection: [ModelsGetGraphqlIntrospectionReq, GraphQlIntrospection | null], models_upsert_graphql_introspection: [ModelsUpsertGraphqlIntrospectionReq, GraphQlIntrospection], models_workspace_models: [ModelsWorkspaceModelsReq, string], cmd_git_checkout: [CmdGitCheckoutReq, string], cmd_git_branch: [CmdGitBranchReq, null], cmd_git_delete_branch: [CmdGitDeleteBranchReq, BranchDeleteResult], cmd_git_delete_remote_branch: [CmdGitDeleteRemoteBranchReq, null], cmd_git_merge_branch: [CmdGitMergeBranchReq, null], cmd_git_rename_branch: [CmdGitRenameBranchReq, null], cmd_git_status: [CmdGitStatusReq, GitStatusSummary], cmd_git_branch_info: [CmdGitBranchInfoReq, GitBranchInfo], cmd_git_worktree_status: [CmdGitWorktreeStatusReq, GitWorktreeStatus], cmd_git_log: [CmdGitLogReq, Array], cmd_git_log_for_file: [CmdGitLogForFileReq, Array], cmd_git_file_diff_for_commit: [CmdGitFileDiffForCommitReq, GitFileDiff], cmd_git_initialize: [CmdGitInitializeReq, null], cmd_git_clone: [CmdGitCloneReq, CloneResult], cmd_git_commit: [CmdGitCommitReq, null], cmd_git_fetch_all: [CmdGitFetchAllReq, null], cmd_git_push: [CmdGitPushReq, PushResult], cmd_git_pull: [CmdGitPullReq, PullResult], cmd_git_pull_force_reset: [CmdGitPullForceResetReq, PullResult], cmd_git_pull_merge: [CmdGitPullMergeReq, PullResult], cmd_git_add: [CmdGitAddReq, null], cmd_git_unstage: [CmdGitUnstageReq, null], cmd_git_reset_changes: [CmdGitResetChangesReq, null], cmd_git_restore_files: [CmdGitRestoreFilesReq, null], cmd_git_restore_file_from_commit: [CmdGitRestoreFileFromCommitReq, null], cmd_git_add_credential: [CmdGitAddCredentialReq, null], cmd_git_remotes: [CmdGitRemotesReq, Array], cmd_git_add_remote: [CmdGitAddRemoteReq, GitRemote], cmd_git_rm_remote: [CmdGitRmRemoteReq, null], cmd_sync_calculate: [CmdSyncCalculateReq, Array], cmd_sync_calculate_fs: [CmdSyncCalculateFsReq, Array], cmd_sync_apply: [CmdSyncApplyReq, boolean], cmd_ws_delete_connections: [CmdWsDeleteConnectionsReq, null], cmd_ws_send: [CmdWsSendReq, WebsocketConnection], cmd_ws_close: [CmdWsCloseReq, WebsocketConnection], cmd_ws_connect: [CmdWsConnectReq, WebsocketConnection], cmd_plugins_search: [CmdPluginsSearchReq, PluginSearchResponse], cmd_plugins_install: [CmdPluginsInstallReq, null], cmd_plugins_install_from_directory: [CmdPluginsInstallFromDirectoryReq, Plugin], cmd_plugins_uninstall: [CmdPluginsUninstallReq, Plugin], cmd_plugin_init_errors: [CmdPluginInitErrorsReq, Array<[string, string]>], cmd_plugins_updates: [CmdPluginsUpdatesReq, PluginUpdatesResponse], cmd_plugins_update_all: [CmdPluginsUpdateAllReq, Array], cmd_git_watch_worktree_status: [CmdGitWatchWorktreeStatusReq, GitWatchResult], cmd_sync_watch: [CmdSyncWatchReq, WatchResult], }; export type WatchResult = { unlistenEvent: string, }; diff --git a/crates/common/yaak-rpc-schema/bindings/gen_search.ts b/crates/common/yaak-rpc-schema/bindings/gen_search.ts index dd3c1ad72..04cb08acf 100644 --- a/crates/common/yaak-rpc-schema/bindings/gen_search.ts +++ b/crates/common/yaak-rpc-schema/bindings/gen_search.ts @@ -1,5 +1,9 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type PluginMetadata = { version: string, name: string, displayName: string, description: string | null, homepageUrl: string | null, repositoryUrl: string | null, }; +export type PluginMetadata = { version: string, name: string, displayName: string, description: string | null, homepageUrl: string | null, repositoryUrl: string | null, +/** + * Why the plugin should no longer be used, from `deprecated` in its package.json + */ +deprecated: string | null, }; -export type PluginVersion = { id: string, version: string, url: string, description: string | null, name: string, displayName: string, homepageUrl: string | null, repositoryUrl: string | null, checksum: string, readme: string | null, yanked: boolean, }; +export type PluginVersion = { id: string, version: string, url: string, description: string | null, name: string, displayName: string, homepageUrl: string | null, repositoryUrl: string | null, checksum: string, readme: string | null, yanked: boolean, deprecated: string | null, }; diff --git a/crates/common/yaak-rpc-schema/src/lib.rs b/crates/common/yaak-rpc-schema/src/lib.rs index 791f0271d..a81fc773e 100644 --- a/crates/common/yaak-rpc-schema/src/lib.rs +++ b/crates/common/yaak-rpc-schema/src/lib.rs @@ -97,6 +97,35 @@ pub struct CmdSyncWatchReq { #[ts(export, export_to = "gen_rpc.ts")] pub struct CmdMetadataReq {} +/// A coding agent the Agents settings pane can set up. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)] +#[serde(rename_all = "snake_case")] +#[ts(export, export_to = "gen_rpc.ts")] +pub enum AgentClient { + ClaudeCode, + Codex, + Cursor, + Vscode, + Other, +} + +#[derive(Debug, Deserialize, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export, export_to = "gen_rpc.ts")] +pub struct CmdAgentSetupStatusReq { + pub agent: AgentClient, +} + +/// Which setup steps an agent already has done on this machine. `None` means +/// the pane cannot tell for that agent. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export, export_to = "gen_rpc.ts")] +pub struct AgentSetupStatus { + pub mcp_server: Option, + pub skill: Option, +} + #[derive(Debug, Deserialize, TS)] #[serde(rename_all = "camelCase")] #[ts(export, export_to = "gen_rpc.ts")] @@ -928,6 +957,7 @@ macro_rules! with_commands { ($callback:ident) => { $callback! { cmd_metadata(CmdMetadataReq) -> AppMetaData, + cmd_agent_setup_status(CmdAgentSetupStatusReq) -> AgentSetupStatus, cmd_template_tokens_to_string(CmdTemplateTokensToStringReq) -> String, cmd_render_template(CmdRenderTemplateReq) -> String, cmd_send_feedback(CmdSendFeedbackReq) -> (), diff --git a/crates/yaak-commands/src/agents.rs b/crates/yaak-commands/src/agents.rs new file mode 100644 index 000000000..5a3642bf1 --- /dev/null +++ b/crates/yaak-commands/src/agents.rs @@ -0,0 +1,317 @@ +//! Which of the Agents pane's setup steps are already done on this machine. +//! +//! Detection reads the files the agents keep their MCP servers in and the +//! skills directory `yaak agent install` writes to. A missing or unparsable +//! file is "not detected", never an error: the pane shows a done mark when it +//! can, and the command when it cannot. + +use serde_json::Value; +use std::path::{Path, PathBuf}; +use yaak_rpc_schema::{AgentClient, AgentSetupStatus}; + +const SKILL_NAME: &str = "use-yaak"; +const SERVER_NAME: &str = "yaak"; + +pub fn agent_setup_status(home: &Path, agent: AgentClient) -> AgentSetupStatus { + AgentSetupStatus { + mcp_server: mcp_server_added(home, agent), + skill: skill_installed(home, agent), + } +} + +fn skill_installed(home: &Path, agent: AgentClient) -> Option { + let skills_dir = match agent { + AgentClient::ClaudeCode => home.join(".claude").join("skills"), + AgentClient::Codex => home.join(".codex").join("skills"), + AgentClient::Cursor => home.join(".cursor").join("skills"), + AgentClient::Vscode | AgentClient::Other => home.join(".agents").join("skills"), + }; + Some(skills_dir.join(SKILL_NAME).is_dir()) +} + +fn mcp_server_added(home: &Path, agent: AgentClient) -> Option { + match agent { + AgentClient::ClaudeCode => Some(claude_code_has_server(&home.join(".claude.json"))), + AgentClient::Codex => Some(codex_has_server(&home.join(".codex").join("config.toml"))), + AgentClient::Cursor => { + Some(json_has_server(&home.join(".cursor").join("mcp.json"), "mcpServers")) + } + AgentClient::Vscode => Some(json_has_server(&vscode_user_mcp_json(home), "servers")), + AgentClient::Other => None, + } +} + +fn vscode_user_mcp_json(home: &Path) -> PathBuf { + let user_dir = if cfg!(target_os = "macos") { + home.join("Library").join("Application Support").join("Code").join("User") + } else if cfg!(target_os = "windows") { + std::env::var_os("APPDATA") + .map(PathBuf::from) + .unwrap_or_else(|| home.join("AppData").join("Roaming")) + .join("Code") + .join("User") + } else { + home.join(".config").join("Code").join("User") + }; + user_dir.join("mcp.json") +} + +fn read_json(path: &Path) -> Option { + let text = std::fs::read_to_string(path).ok()?; + serde_json::from_str(&text).ok() +} + +/// Only the CLI's own entry counts. An entry named `yaak` that points at a +/// URL is the deprecated plugin's server and still needs replacing. +fn has_server(servers: Option<&Value>) -> bool { + servers.and_then(|s| s.get(SERVER_NAME)).is_some_and(is_cli_server) +} + +fn is_cli_server(entry: &Value) -> bool { + let command = entry.get("command").and_then(Value::as_str); + let args: Vec<&str> = entry + .get("args") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + is_cli_launch(command, &args) +} + +/// `yaak mcp`, or `npx -y @yaakapp/cli mcp`, which runs the same binary. +fn is_cli_launch(command: Option<&str>, args: &[&str]) -> bool { + let has_mcp = args.contains(&"mcp"); + let via_npx = command_stem(command) == Some("npx") + && args.iter().any(|a| a.trim_start_matches("@yaakapp/cli").len() < a.len()); + has_mcp && (command_stem(command) == Some("yaak") || via_npx) +} + +fn command_stem(command: Option<&str>) -> Option<&str> { + command.and_then(|c| Path::new(c).file_stem().and_then(|s| s.to_str())) +} + +fn json_has_server(path: &Path, key: &str) -> bool { + read_json(path).is_some_and(|root| has_server(root.get(key))) +} + +/// `claude mcp add` writes to the top level with `-s user` and under the +/// current project's entry without it, so both count. +fn claude_code_has_server(path: &Path) -> bool { + let Some(root) = read_json(path) else { + return false; + }; + if has_server(root.get("mcpServers")) { + return true; + } + root.get("projects") + .and_then(|p| p.as_object()) + .is_some_and(|projects| projects.values().any(|p| has_server(p.get("mcpServers")))) +} + +/// A `[mcp_servers.yaak]` table, key bare or quoted, whose `command` is yaak +/// and whose `args` include mcp. The file is scanned line by line, not parsed. +fn codex_has_server(path: &Path) -> bool { + let Ok(text) = std::fs::read_to_string(path) else { + return false; + }; + let mut in_table = false; + let mut command = None; + let mut args = Vec::new(); + let mut in_args = false; + for line in text.lines().map(str::trim) { + if line.starts_with('[') { + in_table = is_codex_server_header(line); + in_args = false; + } else if in_table { + let rest = if in_args { + Some(line) + } else if let Some((key, value)) = line.split_once('=') { + match key.trim() { + "command" => { + command = Some(value.trim().trim_matches(QUOTES).to_string()); + None + } + "args" => Some(value), + _other => None, + } + } else { + None + }; + if let Some(rest) = rest { + args.extend( + rest.split(',') + .map(|a| a.trim().trim_matches(QUOTES_OR_BRACKETS)) + .filter(|a| !a.is_empty()) + .map(str::to_string), + ); + in_args = !rest.contains(']'); + } + } + } + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + is_cli_launch(command.as_deref(), &args) +} + +const QUOTES: [char; 2] = ['"', '\'']; +const QUOTES_OR_BRACKETS: [char; 4] = ['"', '\'', '[', ']']; + +fn is_codex_server_header(line: &str) -> bool { + let Some(rest) = line.strip_prefix('[') else { + return false; + }; + let Some(inner) = rest.split(']').next() else { + return false; + }; + let mut parts = inner.split('.').map(|p| p.trim().trim_matches(|c| c == '"' || c == '\'')); + parts.next() == Some("mcp_servers") && parts.next() == Some(SERVER_NAME) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + fn write(path: &Path, contents: &str) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, contents).unwrap(); + } + + #[test] + fn nothing_installed() { + let home = tempfile::tempdir().unwrap(); + for agent in [ + AgentClient::ClaudeCode, + AgentClient::Codex, + AgentClient::Cursor, + AgentClient::Vscode, + ] { + let status = agent_setup_status(home.path(), agent); + assert_eq!(status.mcp_server, Some(false), "{agent:?}"); + assert_eq!(status.skill, Some(false), "{agent:?}"); + } + let other = agent_setup_status(home.path(), AgentClient::Other); + assert_eq!(other.mcp_server, None); + assert_eq!(other.skill, Some(false)); + } + + #[test] + fn skill_directories_per_agent() { + let home = tempfile::tempdir().unwrap(); + fs::create_dir_all(home.path().join(".claude/skills/use-yaak")).unwrap(); + fs::create_dir_all(home.path().join(".agents/skills/use-yaak")).unwrap(); + + assert_eq!(agent_setup_status(home.path(), AgentClient::ClaudeCode).skill, Some(true)); + assert_eq!(agent_setup_status(home.path(), AgentClient::Codex).skill, Some(false)); + assert_eq!(agent_setup_status(home.path(), AgentClient::Cursor).skill, Some(false)); + assert_eq!(agent_setup_status(home.path(), AgentClient::Vscode).skill, Some(true)); + assert_eq!(agent_setup_status(home.path(), AgentClient::Other).skill, Some(true)); + } + + #[test] + fn claude_code_top_level_or_project_scope() { + let home = tempfile::tempdir().unwrap(); + let path = home.path().join(".claude.json"); + + write(&path, r#"{"mcpServers":{"yaak":{"command":"yaak","args":["mcp"]}}}"#); + assert_eq!(agent_setup_status(home.path(), AgentClient::ClaudeCode).mcp_server, Some(true)); + + write( + &path, + r#"{"projects":{"/Users/me/app":{"mcpServers":{"yaak":{"command":"/usr/local/bin/yaak","args":["mcp"]}}}}}"#, + ); + assert_eq!(agent_setup_status(home.path(), AgentClient::ClaudeCode).mcp_server, Some(true)); + + write( + &path, + r#"{"mcpServers":{"yaak":{"type":"http","url":"http://127.0.0.1:64343/mcp"}}}"#, + ); + assert_eq!( + agent_setup_status(home.path(), AgentClient::ClaudeCode).mcp_server, + Some(false) + ); + + write(&path, r#"{"mcpServers":{"other":{}},"projects":{"/x":{"mcpServers":{}}}}"#); + assert_eq!( + agent_setup_status(home.path(), AgentClient::ClaudeCode).mcp_server, + Some(false) + ); + + write(&path, "{ not json"); + assert_eq!( + agent_setup_status(home.path(), AgentClient::ClaudeCode).mcp_server, + Some(false) + ); + } + + #[test] + fn codex_table_header() { + let home = tempfile::tempdir().unwrap(); + let path = home.path().join(".codex/config.toml"); + + write( + &path, + "model = \"o3\"\n\n[mcp_servers.yaak]\ncommand = \"yaak\"\nargs = [\"mcp\"]\n", + ); + assert_eq!(agent_setup_status(home.path(), AgentClient::Codex).mcp_server, Some(true)); + + write(&path, " [ mcp_servers . \"yaak\" ]\ncommand = 'yaak'\nargs = ['mcp']\n[other]\n"); + assert_eq!(agent_setup_status(home.path(), AgentClient::Codex).mcp_server, Some(true)); + + write(&path, "[mcp_servers.yaak]\nurl = \"http://127.0.0.1:64343/mcp\"\n"); + assert_eq!(agent_setup_status(home.path(), AgentClient::Codex).mcp_server, Some(false)); + + write(&path, "[mcp_servers.yaak]\ncommand = \"yaak\"\nargs = [\n \"mcp\",\n]\n"); + assert_eq!(agent_setup_status(home.path(), AgentClient::Codex).mcp_server, Some(true)); + + write(&path, "[mcp_servers.yaak.env]\nFOO = \"bar\"\n"); + assert_eq!(agent_setup_status(home.path(), AgentClient::Codex).mcp_server, Some(false)); + + write( + &path, + "[mcp_servers.yaak]\n[mcp_servers.other]\ncommand = \"yaak\"\nargs = [\"mcp\"]\n", + ); + assert_eq!(agent_setup_status(home.path(), AgentClient::Codex).mcp_server, Some(false)); + + write(&path, "[mcp_servers.yaakish]\ncommand = \"x\"\n[mcp_servers]\n"); + assert_eq!(agent_setup_status(home.path(), AgentClient::Codex).mcp_server, Some(false)); + } + + #[test] + fn cursor_and_vscode_json() { + let home = tempfile::tempdir().unwrap(); + + write( + &home.path().join(".cursor/mcp.json"), + r#"{"mcpServers":{"yaak":{"command":"yaak","args":["mcp"]}}}"#, + ); + assert_eq!(agent_setup_status(home.path(), AgentClient::Cursor).mcp_server, Some(true)); + + write( + &home.path().join(".cursor/mcp.json"), + r#"{"mcpServers":{"yaak":{"url":"http://127.0.0.1:64343/mcp"}}}"#, + ); + assert_eq!(agent_setup_status(home.path(), AgentClient::Cursor).mcp_server, Some(false)); + + write( + &home.path().join(".cursor/mcp.json"), + r#"{"mcpServers":{"yaak":{"command":"npx","args":["-y","@yaakapp/cli","mcp"]}}}"#, + ); + assert_eq!(agent_setup_status(home.path(), AgentClient::Cursor).mcp_server, Some(true)); + + write( + &home.path().join(".cursor/mcp.json"), + r#"{"mcpServers":{"yaak":{"command":"npx","args":["-y","mcp-remote","http://127.0.0.1:64343/mcp"]}}}"#, + ); + assert_eq!(agent_setup_status(home.path(), AgentClient::Cursor).mcp_server, Some(false)); + + write(&home.path().join(".cursor/mcp.json"), r#"{"servers":{"yaak":{}}}"#); + assert_eq!(agent_setup_status(home.path(), AgentClient::Cursor).mcp_server, Some(false)); + + if !cfg!(target_os = "windows") { + write( + &vscode_user_mcp_json(home.path()), + r#"{"servers":{"yaak":{"type":"stdio","command":"yaak","args":["mcp"]}}}"#, + ); + assert_eq!(agent_setup_status(home.path(), AgentClient::Vscode).mcp_server, Some(true)); + } + } +} diff --git a/crates/yaak-commands/src/lib.rs b/crates/yaak-commands/src/lib.rs index 72563c207..7be82edd6 100644 --- a/crates/yaak-commands/src/lib.rs +++ b/crates/yaak-commands/src/lib.rs @@ -12,6 +12,7 @@ //! can serve (native windows, the updater, dialogs) or that still lean on it. pub mod actions; +pub mod agents; pub mod auth; pub mod data; pub mod encryption; diff --git a/crates/yaak-commands/src/plugins.rs b/crates/yaak-commands/src/plugins.rs index 0971f930a..cbf1c4ee5 100644 --- a/crates/yaak-commands/src/plugins.rs +++ b/crates/yaak-commands/src/plugins.rs @@ -37,6 +37,7 @@ fn fallback_plugin_metadata(directory: &str) -> PluginMetadata { description: Some(format!("Plugin metadata could not be loaded from {directory}")), homepage_url: None, repository_url: None, + deprecated: None, } } diff --git a/crates/yaak-mcp/src/lib.rs b/crates/yaak-mcp/src/lib.rs index af40d7ec9..176cda2c6 100644 --- a/crates/yaak-mcp/src/lib.rs +++ b/crates/yaak-mcp/src/lib.rs @@ -1,5 +1,6 @@ //! Yaak's MCP server: the tools, written once against [`McpHost`], and the -//! transports the app (streamable HTTP) and the CLI (stdio) serve them on. +//! transports the CLI serves them on: stdio by default, streamable HTTP with +//! `yaak mcp --http`. pub mod http; mod params; diff --git a/crates/yaak-plugins/bindings/gen_search.ts b/crates/yaak-plugins/bindings/gen_search.ts index dd3c1ad72..04cb08acf 100644 --- a/crates/yaak-plugins/bindings/gen_search.ts +++ b/crates/yaak-plugins/bindings/gen_search.ts @@ -1,5 +1,9 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type PluginMetadata = { version: string, name: string, displayName: string, description: string | null, homepageUrl: string | null, repositoryUrl: string | null, }; +export type PluginMetadata = { version: string, name: string, displayName: string, description: string | null, homepageUrl: string | null, repositoryUrl: string | null, +/** + * Why the plugin should no longer be used, from `deprecated` in its package.json + */ +deprecated: string | null, }; -export type PluginVersion = { id: string, version: string, url: string, description: string | null, name: string, displayName: string, homepageUrl: string | null, repositoryUrl: string | null, checksum: string, readme: string | null, yanked: boolean, }; +export type PluginVersion = { id: string, version: string, url: string, description: string | null, name: string, displayName: string, homepageUrl: string | null, repositoryUrl: string | null, checksum: string, readme: string | null, yanked: boolean, deprecated: string | null, }; diff --git a/crates/yaak-plugins/src/api.rs b/crates/yaak-plugins/src/api.rs index f09f92c1d..02934cafc 100644 --- a/crates/yaak-plugins/src/api.rs +++ b/crates/yaak-plugins/src/api.rs @@ -109,7 +109,10 @@ pub struct PluginVersion { pub repository_url: Option, pub checksum: String, pub readme: Option, + #[serde(default)] pub yanked: bool, + #[serde(default)] + pub deprecated: Option, } #[derive(Debug, Clone, Serialize, Deserialize, TS, PartialEq)] diff --git a/crates/yaak-plugins/src/plugin_meta.rs b/crates/yaak-plugins/src/plugin_meta.rs index 13cd3b2f1..c89766e23 100644 --- a/crates/yaak-plugins/src/plugin_meta.rs +++ b/crates/yaak-plugins/src/plugin_meta.rs @@ -14,6 +14,8 @@ pub struct PluginMetadata { pub description: Option, pub homepage_url: Option, pub repository_url: Option, + /// Why the plugin should no longer be used, from `deprecated` in its package.json + pub deprecated: Option, } pub fn get_plugin_meta(plugin_dir: &Path) -> Result { @@ -37,6 +39,7 @@ pub fn get_plugin_meta(plugin_dir: &Path) -> Result { name: package_json.name, display_name, homepage_url: package_json.homepage, + deprecated: package_json.deprecated, repository_url: match package_json.repository { None => None, Some(RepositoryField::Object { url }) => Some(url), @@ -54,6 +57,7 @@ struct PackageJson { pub repository: Option, pub homepage: Option, pub description: Option, + pub deprecated: Option, } #[derive(Debug, Deserialize)] diff --git a/packages/platform/src/types.ts b/packages/platform/src/types.ts index 51d4e0b0f..eaf704f06 100644 --- a/packages/platform/src/types.ts +++ b/packages/platform/src/types.ts @@ -313,7 +313,7 @@ export interface PlatformCapabilities { systemFonts: boolean; /** Commercial licence activation. */ license: boolean; - /** Connecting local AI agents: the Yaak CLI on this machine and the app's own MCP server. */ + /** Connecting local AI agents through the Yaak CLI on this machine. */ agents: boolean; } diff --git a/packages/plugin-runtime-types/src/bindings/gen_models.ts b/packages/plugin-runtime-types/src/bindings/gen_models.ts index c03e2595a..af89495bd 100644 --- a/packages/plugin-runtime-types/src/bindings/gen_models.ts +++ b/packages/plugin-runtime-types/src/bindings/gen_models.ts @@ -398,6 +398,7 @@ export type Settings = { updateChannel: string; hideLicenseBadge: boolean; promptFeedback: boolean; + mcpServerEnabled: boolean; autoupdate: boolean; autoDownloadUpdates: boolean; checkNotifications: boolean; diff --git a/packages/plugin-runtime-types/src/bindings/gen_search.ts b/packages/plugin-runtime-types/src/bindings/gen_search.ts index dd3c1ad72..04cb08acf 100644 --- a/packages/plugin-runtime-types/src/bindings/gen_search.ts +++ b/packages/plugin-runtime-types/src/bindings/gen_search.ts @@ -1,5 +1,9 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type PluginMetadata = { version: string, name: string, displayName: string, description: string | null, homepageUrl: string | null, repositoryUrl: string | null, }; +export type PluginMetadata = { version: string, name: string, displayName: string, description: string | null, homepageUrl: string | null, repositoryUrl: string | null, +/** + * Why the plugin should no longer be used, from `deprecated` in its package.json + */ +deprecated: string | null, }; -export type PluginVersion = { id: string, version: string, url: string, description: string | null, name: string, displayName: string, homepageUrl: string | null, repositoryUrl: string | null, checksum: string, readme: string | null, yanked: boolean, }; +export type PluginVersion = { id: string, version: string, url: string, description: string | null, name: string, displayName: string, homepageUrl: string | null, repositoryUrl: string | null, checksum: string, readme: string | null, yanked: boolean, deprecated: string | null, }; diff --git a/plugins-external/mcp-server/README.md b/plugins-external/mcp-server/README.md index c2d9c84ba..3653cda2f 100644 --- a/plugins-external/mcp-server/README.md +++ b/plugins-external/mcp-server/README.md @@ -2,8 +2,9 @@ Exposes Yaak's functionality via the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/). -**Deprecated.** Yaak now has a built-in MCP server with the same tools. Uninstall this plugin, -then turn the server on in Settings > Agents, or run `yaak mcp` from the Yaak CLI. +**Deprecated.** The Yaak CLI serves the same tools with `yaak mcp`, with the app open or +closed. Install the CLI (`npm install -g @yaakapp/cli`), point your agent at `yaak mcp`, then +uninstall this plugin. Settings > Agents in Yaak has the command for each agent. ## Setup @@ -13,14 +14,14 @@ Add this to your Claude Desktop config (`~/Library/Application Support/Claude/cl { "mcpServers": { "yaak": { - "command": "npx", - "args": ["-y", "mcp-remote", "http://127.0.0.1:64343/mcp"] + "command": "yaak", + "args": ["mcp"] } } } ``` -Restart Claude Desktop and make sure Yaak is running. +Restart Claude Desktop. ## Available Tools diff --git a/plugins-external/mcp-server/package.json b/plugins-external/mcp-server/package.json index 5a679d8b4..ca45c70fd 100644 --- a/plugins-external/mcp-server/package.json +++ b/plugins-external/mcp-server/package.json @@ -1,9 +1,10 @@ { "name": "@yaak/mcp-server", "displayName": "MCP Server", - "version": "0.2.2", + "version": "0.2.3", "private": true, "description": "Expose Yaak functionality via Model Context Protocol", + "deprecated": "Replaced by the built-in `yaak mcp` in the Yaak CLI. Install the CLI instead.", "repository": { "type": "git", "url": "https://github.com/mountain-loop/yaak.git", diff --git a/plugins-external/mcp-server/src/index.ts b/plugins-external/mcp-server/src/index.ts index 2da1a6b6f..4793411da 100644 --- a/plugins-external/mcp-server/src/index.ts +++ b/plugins-external/mcp-server/src/index.ts @@ -13,7 +13,7 @@ export const plugin: PluginDefinition = { setTimeout(async () => { void ctx.toast.show({ message: - "The MCP Server plugin is deprecated. Yaak now has a built-in MCP server: uninstall this plugin, then turn it on in Settings > Agents.", + "The MCP Server plugin is deprecated. Install the Yaak CLI, point your agent at `yaak mcp`, then uninstall this plugin.", icon: "alert_triangle", color: "notice", timeout: 30000,