@saadnvd1/agent-os 0.3.664 → 0.3.672

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/app/api/audits/[kind]/[id]/route.test.ts +2 -2
  2. package/app/api/mcp-auth/callback/route.test.ts +42 -0
  3. package/app/api/mcp-auth/callback/route.ts +56 -0
  4. package/app/api/projects/[id]/route.ts +26 -0
  5. package/app/api/projects/init/route.test.ts +2 -4
  6. package/app/api/sessions/[id]/mcp-auth/route.test.ts +86 -0
  7. package/app/api/sessions/[id]/mcp-auth/route.ts +58 -0
  8. package/app/api/shares/route.test.ts +3 -4
  9. package/app/api/workspaces/[id]/route.ts +9 -1
  10. package/app/api/worktree-sweep/route.test.ts +21 -0
  11. package/app/api/worktree-sweep/route.ts +24 -4
  12. package/components/Chat/ChatPanel.tsx +6 -3
  13. package/components/Chat/McpServers.tsx +61 -24
  14. package/components/Chat/McpSignIn.tsx +122 -0
  15. package/components/Chat/session.ts +8 -0
  16. package/components/Health/SweepRuns.tsx +1 -0
  17. package/components/Projects/ProjectSettingsDialog.tsx +7 -0
  18. package/components/Projects/ProjectTierField.tsx +39 -0
  19. package/components/Workspaces/ProjectTiersForm.tsx +33 -0
  20. package/components/Workspaces/WorkspaceSettings.tsx +8 -0
  21. package/data/chat/mcpAuth.ts +42 -0
  22. package/data/projects/queries.ts +4 -0
  23. package/data/workspaces/index.ts +6 -0
  24. package/lib/chat/driver.ts +24 -2
  25. package/lib/chat/drivers/claude-approvals.ts +7 -0
  26. package/lib/chat/drivers/claude-mcp-auth.ts +82 -0
  27. package/lib/chat/drivers/claude.ts +7 -0
  28. package/lib/chat/events.ts +12 -0
  29. package/lib/chat/mcp-auth.ts +193 -0
  30. package/lib/chat/registry.ts +2 -0
  31. package/lib/chat/runner.ts +18 -0
  32. package/lib/chat/worker/client.ts +35 -1
  33. package/lib/chat/worker/host.ts +9 -0
  34. package/lib/chat/worker/main.ts +1 -1
  35. package/lib/chat/worker/mcp-auth.ts +119 -0
  36. package/lib/chat/worker/protocol.ts +19 -0
  37. package/lib/db/migrations/20261018T1730_mcp_sign_ins.ts +22 -0
  38. package/lib/db/migrations/20261018T2100_orch_full_access.ts +16 -0
  39. package/lib/db/migrations/20261018T2130_project_tier.ts +38 -0
  40. package/lib/db/types.ts +7 -0
  41. package/lib/done/testing.ts +2 -2
  42. package/lib/env-setup.ts +8 -1
  43. package/lib/health/boots.ts +2 -8
  44. package/lib/orchestrator/armed.test-helpers.ts +7 -2
  45. package/lib/orchestrator/armed.ts +14 -1
  46. package/lib/orchestrator/brief.ts +23 -11
  47. package/lib/orchestrator/external-gates.ts +62 -1
  48. package/lib/orchestrator/fast-lane-state.ts +69 -0
  49. package/lib/orchestrator/fast-lane.ts +96 -0
  50. package/lib/orchestrator/full-access.ts +21 -0
  51. package/lib/orchestrator/gates.ts +8 -2
  52. package/lib/orchestrator/project-tier-tool.ts +33 -0
  53. package/lib/orchestrator/quick.ts +47 -4
  54. package/lib/orchestrator/review.ts +3 -0
  55. package/lib/orchestrator/serve.ts +17 -3
  56. package/lib/orchestrator/shell-guard.ts +23 -1
  57. package/lib/orchestrator/signoff.test-helpers.ts +6 -2
  58. package/lib/orchestrator/signoff.ts +36 -19
  59. package/lib/orchestrator/sweep-arm.ts +180 -0
  60. package/lib/orchestrator/tool-names.ts +5 -1
  61. package/lib/orchestrator/tool-schemas.ts +41 -2
  62. package/lib/orchestrator/tools.ts +8 -2
  63. package/lib/orchestrator/watcher.ts +5 -0
  64. package/lib/orchestrator/write-guard.ts +34 -7
  65. package/lib/project-config/brief.ts +3 -1
  66. package/lib/project-config/database.ts +6 -0
  67. package/lib/project-config/index.ts +108 -21
  68. package/lib/project-config/schema.ts +10 -4
  69. package/lib/project-config/session.ts +9 -6
  70. package/lib/project-tier/getProjectTier.ts +18 -0
  71. package/lib/project-tier/index.ts +3 -0
  72. package/lib/project-tier/setProjectTier.ts +14 -0
  73. package/lib/project-tier/types.ts +3 -0
  74. package/lib/security/net.ts +7 -4
  75. package/lib/start-options.ts +8 -1
  76. package/lib/tasks/finish.ts +2 -1
  77. package/lib/tasks/index.ts +10 -5
  78. package/lib/tasks/move-testing.ts +2 -2
  79. package/lib/tasks/state.ts +7 -1
  80. package/lib/test-temp.ts +30 -0
  81. package/lib/workspaces.ts +6 -2
  82. package/lib/worktree-sweep/caches.ts +6 -0
  83. package/lib/worktree-sweep/extras.ts +16 -8
  84. package/lib/worktree-sweep/report.ts +1 -0
  85. package/lib/worktree-sweep/settings.ts +2 -2
  86. package/lib/worktree-sweep/testTemp.ts +113 -0
  87. package/lib/worktree-sweep/types.ts +2 -0
  88. package/package.json +1 -1
  89. package/scripts/autodeploy.test.ts +2 -2
  90. package/scripts/check-bundle.test.ts +2 -2
  91. package/scripts/hooks/banned-terms.test.ts +3 -2
  92. package/scripts/hooks/staged-secrets.test.ts +2 -2
  93. package/scripts/lib/build-swap.test.ts +2 -3
  94. package/scripts/lib/wsl.test.ts +2 -3
  95. package/scripts/update-run.test.ts +2 -2
@@ -0,0 +1,122 @@
1
+ "use client";
2
+
3
+ import { useState } from "react";
4
+ import { ExternalLink } from "lucide-react";
5
+ import type { useMcpSignIn } from "@/data/chat/mcpAuth";
6
+
7
+ const LINK =
8
+ "bg-primary text-primary-foreground inline-flex h-11 items-center justify-center gap-2 rounded-lg px-4 text-sm font-medium md:h-9";
9
+ const GHOST =
10
+ "text-muted-foreground hover:text-foreground h-11 rounded-lg px-3 text-xs md:h-9";
11
+
12
+ // What happens after Sign in is pressed on one server: the link to open, and
13
+ // what to do if the provider can't return to AgentOS by itself. The list row
14
+ // turns connected on its own, over the chat socket, when it's done.
15
+ export function McpSignIn({
16
+ flow: { start, finish, recheck },
17
+ server,
18
+ onClose,
19
+ }: {
20
+ // Started by the Sign in press (not on mount: a dev double-mount would
21
+ // drop the request's result).
22
+ flow: ReturnType<typeof useMcpSignIn>;
23
+ server: string;
24
+ onClose: () => void;
25
+ }) {
26
+ const [pasted, setPasted] = useState("");
27
+
28
+ const mode = start.data?.mode;
29
+ const authUrl = start.data?.authUrl;
30
+ const error = start.error ?? finish.error ?? recheck.error;
31
+ const busy = start.isPending || finish.isPending || recheck.isPending;
32
+
33
+ return (
34
+ <div className="space-y-2 pt-1 pr-2 pb-2 pl-6.5 text-xs">
35
+ {start.isPending && (
36
+ <p className="text-muted-foreground">Starting sign-in…</p>
37
+ )}
38
+ {mode === "done" && (
39
+ <p className="text-muted-foreground">
40
+ Already signed in; reconnecting.
41
+ </p>
42
+ )}
43
+ {(mode === "callback" || mode === "paste" || mode === "external") &&
44
+ authUrl && (
45
+ <div className="flex flex-wrap items-center gap-2">
46
+ <a
47
+ href={authUrl}
48
+ target="_blank"
49
+ rel="noopener noreferrer"
50
+ className={LINK}
51
+ >
52
+ {mode === "external" ? "Open claude.ai" : "Open sign-in page"}
53
+ <ExternalLink className="size-4" />
54
+ </a>
55
+ {mode === "external" && (
56
+ <button
57
+ type="button"
58
+ disabled={busy}
59
+ onClick={() => recheck.mutate()}
60
+ className={GHOST}
61
+ >
62
+ Check again
63
+ </button>
64
+ )}
65
+ </div>
66
+ )}
67
+ {mode === "callback" && (
68
+ <p className="text-muted-foreground">
69
+ Approve it there. This list updates by itself.
70
+ </p>
71
+ )}
72
+ {mode === "external" && (
73
+ <p className="text-muted-foreground">
74
+ This server signs in on claude.ai. Finish there, then come back.
75
+ </p>
76
+ )}
77
+ {mode === "paste" && (
78
+ <>
79
+ <p className="text-muted-foreground">
80
+ This server only sends the sign-in back to the machine running the
81
+ session. On this device the page you land on won&apos;t load: copy
82
+ its address and paste it here.
83
+ </p>
84
+ <form
85
+ className="flex items-center gap-2"
86
+ onSubmit={(e) => {
87
+ e.preventDefault();
88
+ if (pasted.trim()) finish.mutate(pasted.trim());
89
+ }}
90
+ >
91
+ <input
92
+ value={pasted}
93
+ onChange={(e) => setPasted(e.target.value)}
94
+ inputMode="url"
95
+ autoComplete="off"
96
+ autoCapitalize="off"
97
+ spellCheck={false}
98
+ placeholder="Address of the page after approving"
99
+ aria-label={`Address after signing in to ${server}`}
100
+ className="bg-background hairline h-11 min-w-0 flex-1 rounded-lg px-3 text-base md:h-9 md:text-xs"
101
+ />
102
+ <button
103
+ type="submit"
104
+ disabled={busy || !pasted.trim()}
105
+ className="bg-secondary text-secondary-foreground hairline h-11 shrink-0 rounded-lg px-3 text-xs font-medium disabled:opacity-50 md:h-9"
106
+ >
107
+ Finish
108
+ </button>
109
+ </form>
110
+ </>
111
+ )}
112
+ {error && (
113
+ <p className="text-destructive whitespace-pre-wrap" role="alert">
114
+ {error.message}
115
+ </p>
116
+ )}
117
+ <button type="button" onClick={onClose} className={GHOST}>
118
+ {error ? "Close" : "Cancel"}
119
+ </button>
120
+ </div>
121
+ );
122
+ }
@@ -0,0 +1,8 @@
1
+ "use client";
2
+
3
+ import { createContext, useContext } from "react";
4
+
5
+ // The session this chat belongs to, for rows that call its API (a context,
6
+ // not a prop through every item).
7
+ export const ChatSessionId = createContext<string | null>(null);
8
+ export const useChatSessionId = () => useContext(ChatSessionId);
@@ -17,6 +17,7 @@ const KIND: Record<string, string> = {
17
17
  database: "task database",
18
18
  spare: "dependency spare",
19
19
  temp: "temp folder",
20
+ "test-temp": "test temp folder",
20
21
  "derived-data": "Xcode build folder",
21
22
  };
22
23
 
@@ -12,6 +12,8 @@ import {
12
12
  import { Button } from "@/components/ui/button";
13
13
  import { Input } from "@/components/ui/input";
14
14
  import { Textarea } from "@/components/ui/textarea";
15
+ import { ProjectTierField } from "./ProjectTierField";
16
+ import type { ProjectTier } from "@/lib/project-tier/types";
15
17
  import {
16
18
  Select,
17
19
  SelectContent,
@@ -95,6 +97,7 @@ export function ProjectSettingsDialog({
95
97
  getDefaultModelForAgent("claude")
96
98
  );
97
99
  const [initialPrompt, setInitialPrompt] = useState("");
100
+ const [tier, setTier] = useState<ProjectTier>("fast");
98
101
  const [devServers, setDevServers] = useState<DevServerConfig[]>([]);
99
102
  const [repositories, setRepositories] = useState<RepositoryConfig[]>([]);
100
103
  const [isLoading, setIsLoading] = useState(false);
@@ -118,6 +121,7 @@ export function ProjectSettingsDialog({
118
121
  setName(project.name);
119
122
  setWorkingDirectory(project.working_directory);
120
123
  setAgentType(project.agent_type);
124
+ setTier(project.tier);
121
125
  setDefaultModel(
122
126
  isSupportedModelForAgent(project.agent_type, project.default_model)
123
127
  ? project.default_model
@@ -336,6 +340,7 @@ export function ProjectSettingsDialog({
336
340
  agentType,
337
341
  defaultModel,
338
342
  initialPrompt: initialPrompt.trim() || null,
343
+ tier,
339
344
  });
340
345
 
341
346
  // Handle dev server changes
@@ -526,6 +531,8 @@ export function ProjectSettingsDialog({
526
531
  </Select>
527
532
  </div>
528
533
 
534
+ <ProjectTierField value={tier} onChange={setTier} />
535
+
529
536
  {/* Initial Prompt */}
530
537
  <div className="space-y-2">
531
538
  <label className="text-sm font-medium">Initial Prompt</label>
@@ -0,0 +1,39 @@
1
+ "use client";
2
+
3
+ import {
4
+ Select,
5
+ SelectContent,
6
+ SelectItem,
7
+ SelectTrigger,
8
+ SelectValue,
9
+ } from "@/components/ui/select";
10
+ import type { ProjectTier } from "@/lib/project-tier/types";
11
+
12
+ const DETAIL: Record<ProjectTier, string> = {
13
+ production: "CI, the independent review and scope must pass before a merge.",
14
+ fast: "A task's PR merges as soon as it opens: no CI wait, no review.",
15
+ };
16
+
17
+ export function ProjectTierField({
18
+ value,
19
+ onChange,
20
+ }: {
21
+ value: ProjectTier;
22
+ onChange: (tier: ProjectTier) => void;
23
+ }) {
24
+ return (
25
+ <div className="space-y-2">
26
+ <label className="text-sm font-medium">Tier</label>
27
+ <Select value={value} onValueChange={(v) => onChange(v as ProjectTier)}>
28
+ <SelectTrigger>
29
+ <SelectValue />
30
+ </SelectTrigger>
31
+ <SelectContent>
32
+ <SelectItem value="fast">Fast</SelectItem>
33
+ <SelectItem value="production">Production</SelectItem>
34
+ </SelectContent>
35
+ </Select>
36
+ <p className="text-muted-foreground text-xs">{DETAIL[value]}</p>
37
+ </div>
38
+ );
39
+ }
@@ -0,0 +1,33 @@
1
+ "use client";
2
+
3
+ import { SettingToggle } from "@/components/Settings/SettingToggle";
4
+ import { useProjectsQuery, useUpdateProject } from "@/data/projects";
5
+
6
+ // A workspace's projects, each switched between production (every merge gate)
7
+ // and fast (a task's PR merges as soon as it opens).
8
+ export function ProjectTiersForm({ workspaceId }: { workspaceId: string }) {
9
+ const { data: projects } = useProjectsQuery();
10
+ const update = useUpdateProject();
11
+ const mine = (projects ?? []).filter(
12
+ (p) => p.workspace_id === workspaceId && !p.is_uncategorized
13
+ );
14
+ if (!mine.length) return null;
15
+ return (
16
+ <div className="space-y-2">
17
+ {mine.map((p) => (
18
+ <SettingToggle
19
+ key={p.id}
20
+ title={`${p.name}: production`}
21
+ detail="On: CI, the independent review and scope gate its merges. Off (fast): a task's PR merges as soon as it opens."
22
+ checked={p.tier === "production"}
23
+ onChange={(on) =>
24
+ update.mutate({
25
+ projectId: p.id,
26
+ tier: on ? "production" : "fast",
27
+ })
28
+ }
29
+ />
30
+ ))}
31
+ </div>
32
+ );
33
+ }
@@ -7,6 +7,7 @@ import { RulesForm } from "./RulesForm";
7
7
  import { FreshStartForm } from "./FreshStartForm";
8
8
  import { McpServersForm } from "./McpServersForm";
9
9
  import { HqFolderForm } from "./HqFolderForm";
10
+ import { ProjectTiersForm } from "./ProjectTiersForm";
10
11
  import { StallForm } from "./StallForm";
11
12
  import { WorkspaceModelsForm } from "./WorkspaceModelsForm";
12
13
  import { AwayWindowForm } from "@/components/Away/AwayWindowForm";
@@ -49,12 +50,19 @@ export function WorkspaceSettings() {
49
50
  <WorkspaceModelsForm workspaceId={w.id} />
50
51
  <McpServersForm workspace={w} />
51
52
  <HqFolderForm workspaceId={w.id} />
53
+ <ProjectTiersForm workspaceId={w.id} />
52
54
  <SettingToggle
53
55
  title="Wake tasks on CI failures and reviews"
54
56
  detail="A task's agent is messaged once when a check fails on its PR's head, with the log's tail, and when someone reviews or comments on it."
55
57
  checked={w.wake_tasks_on_pr}
56
58
  onChange={(on) => update.mutate({ id: w.id, wakeTasksOnPR: on })}
57
59
  />
60
+ <SettingToggle
61
+ title="Orchestrator full access"
62
+ detail="Its shell and file writes aren't checked: it can push, commit, edit any repository or file on this machine, and merge a PR directly. Off: the deny list, write limits, quick-change cap and merge-only-through-the-gates apply."
63
+ checked={w.orch_full_access}
64
+ onChange={(on) => update.mutate({ id: w.id, orchFullAccess: on })}
65
+ />
58
66
  </section>
59
67
  ))}
60
68
  <FreshStartForm />
@@ -0,0 +1,42 @@
1
+ import { useMutation } from "@tanstack/react-query";
2
+ import type { McpSignInStart } from "@/lib/chat/events";
3
+
4
+ type Body = {
5
+ action: "start" | "submit" | "reconnect";
6
+ server: string;
7
+ itemId: string;
8
+ url?: string;
9
+ };
10
+
11
+ async function post<T>(sessionId: string, body: Body): Promise<T> {
12
+ const res = await fetch(`/api/sessions/${sessionId}/mcp-auth`, {
13
+ method: "POST",
14
+ headers: { "Content-Type": "application/json" },
15
+ body: JSON.stringify(body),
16
+ });
17
+ const data = await res.json().catch(() => ({}));
18
+ if (!res.ok) throw new Error(data.error || `Request failed (${res.status})`);
19
+ return data as T;
20
+ }
21
+
22
+ // Sign in to one MCP server of a chat's /mcp list. The list itself updates
23
+ // over the chat socket once the server is back.
24
+ export function useMcpSignIn(
25
+ sessionId: string,
26
+ itemId: string,
27
+ server: string
28
+ ) {
29
+ const start = useMutation({
30
+ mutationFn: () =>
31
+ post<McpSignInStart>(sessionId, { action: "start", server, itemId }),
32
+ });
33
+ const finish = useMutation({
34
+ mutationFn: (url: string) =>
35
+ post<{ ok: true }>(sessionId, { action: "submit", server, itemId, url }),
36
+ });
37
+ const recheck = useMutation({
38
+ mutationFn: () =>
39
+ post<{ ok: true }>(sessionId, { action: "reconnect", server, itemId }),
40
+ });
41
+ return { start, finish, recheck };
42
+ }
@@ -3,6 +3,7 @@ import type {
3
3
  ProjectWithRepositories,
4
4
  DetectedDevServer,
5
5
  } from "@/lib/projects";
6
+ import type { ProjectTier } from "@/lib/db/types";
6
7
  import { projectKeys } from "./keys";
7
8
  import { sessionKeys } from "../sessions/keys";
8
9
 
@@ -131,6 +132,7 @@ export function useUpdateProject() {
131
132
  agentType,
132
133
  defaultModel,
133
134
  initialPrompt,
135
+ tier,
134
136
  }: {
135
137
  projectId: string;
136
138
  name?: string;
@@ -138,6 +140,7 @@ export function useUpdateProject() {
138
140
  agentType?: string;
139
141
  defaultModel?: string;
140
142
  initialPrompt?: string | null;
143
+ tier?: ProjectTier;
141
144
  }) => {
142
145
  const res = await fetch(`/api/projects/${projectId}`, {
143
146
  method: "PATCH",
@@ -148,6 +151,7 @@ export function useUpdateProject() {
148
151
  agentType,
149
152
  defaultModel,
150
153
  initialPrompt,
154
+ tier,
151
155
  }),
152
156
  });
153
157
  if (!res.ok) throw new Error("Failed to update project");
@@ -66,6 +66,8 @@ export function useUpdateWorkspace() {
66
66
  maxRunningTasks?: number | null;
67
67
  // Message tasks about failing checks and reviews on their PRs.
68
68
  wakeTasksOnPR?: boolean;
69
+ // Its orchestrator runs without guards.
70
+ orchFullAccess?: boolean;
69
71
  // MCP servers its orchestrator may use, by name.
70
72
  mcpServers?: string[];
71
73
  }) =>
@@ -80,6 +82,7 @@ export function useUpdateWorkspace() {
80
82
  id,
81
83
  maxRunningTasks,
82
84
  wakeTasksOnPR,
85
+ orchFullAccess,
83
86
  mcpServers,
84
87
  ...updates
85
88
  }) => {
@@ -96,6 +99,9 @@ export function useUpdateWorkspace() {
96
99
  ...(wakeTasksOnPR !== undefined && {
97
100
  wake_tasks_on_pr: wakeTasksOnPR,
98
101
  }),
102
+ ...(orchFullAccess !== undefined && {
103
+ orch_full_access: orchFullAccess,
104
+ }),
99
105
  ...(mcpServers !== undefined && {
100
106
  orch_mcp_servers: mcpServers,
101
107
  }),
@@ -11,9 +11,26 @@ import type {
11
11
  ChatModel,
12
12
  DriverEvent,
13
13
  FileSuggestion,
14
+ McpServerView,
15
+ McpSignInStart,
14
16
  UndoPreview,
15
17
  } from "./events";
16
18
 
19
+ // An agent's way of signing in to an MCP server that needs it, without
20
+ // restarting the conversation. Tokens stay with the agent; the host only
21
+ // sees the link to open and, later, the address the provider returned to.
22
+ export interface McpAuth {
23
+ // `state` ties the provider's return to this attempt; it stays server-side.
24
+ start(
25
+ server: string,
26
+ redirectUri?: string
27
+ ): Promise<McpSignInStart & { state?: string }>;
28
+ // Hands over the address the provider returned the browser to.
29
+ submit(server: string, callbackUrl: string): Promise<void>;
30
+ reconnect(server: string): Promise<void>;
31
+ servers(): Promise<McpServerView[]>;
32
+ }
33
+
17
34
  export interface ChatStartOptions {
18
35
  cwd: string;
19
36
  model: string;
@@ -39,7 +56,8 @@ export interface ChatStartOptions {
39
56
  // can't be changed for this conversation.
40
57
  permissionMode?: PermissionMode;
41
58
  // Checked before every tool call, whatever the permissions say: why it's
42
- // refused, or null to let it go on to them.
59
+ // refused, null to let it go on to them, or a warning the agent is shown
60
+ // while the call still goes on.
43
61
  toolGuard?: ToolGuard;
44
62
  // The note handed back to the agent right after its context is compacted
45
63
  // (lib/chat/compact-context), empty for none. Only Claude Code has a hook
@@ -47,10 +65,12 @@ export interface ChatStartOptions {
47
65
  compactContext?: () => Promise<string>;
48
66
  }
49
67
 
68
+ export type ToolGuardResult = string | null | { warning: string };
69
+
50
70
  export type ToolGuard = (
51
71
  tool: string,
52
72
  input: Record<string, unknown>
53
- ) => Promise<string | null>;
73
+ ) => Promise<ToolGuardResult>;
54
74
 
55
75
  // One live conversation with an agent. Messages sent while a turn runs are
56
76
  // queued by the provider and folded into the conversation.
@@ -88,6 +108,8 @@ export interface ChatConversation {
88
108
  backgroundTask?(toolUseId?: string): Promise<boolean>;
89
109
  // Puts files back as they were before a message (dryRun: only say what).
90
110
  undo(checkpoint: string, dryRun: boolean): Promise<UndoResult>;
111
+ // Signing in to an MCP server that needs it (Claude's).
112
+ mcpAuth?: McpAuth;
91
113
  close(): void;
92
114
  events: AsyncIterable<DriverEvent>;
93
115
  }
@@ -248,6 +248,13 @@ export function guardHook(guard: ToolGuard): HookCallback {
248
248
  (input.tool_input ?? {}) as Record<string, unknown>
249
249
  ).catch((e: Error) => `Couldn't check this call: ${e.message}`);
250
250
  if (reason === null) return {};
251
+ if (typeof reason !== "string")
252
+ return {
253
+ hookSpecificOutput: {
254
+ hookEventName: "PreToolUse",
255
+ additionalContext: reason.warning,
256
+ },
257
+ };
251
258
  return {
252
259
  hookSpecificOutput: {
253
260
  hookEventName: "PreToolUse",
@@ -0,0 +1,82 @@
1
+ import type { McpServerStatus, Query } from "@anthropic-ai/claude-agent-sdk";
2
+ import type { McpAuth } from "../driver";
3
+ import type { McpServerView, McpSignInStart } from "../events";
4
+
5
+ // The CLI takes these as control requests and the SDK's Query has the
6
+ // methods, but its type declarations don't list them.
7
+ type AuthQuery = Query & {
8
+ mcpAuthenticate?(server: string, redirectUri?: string): Promise<unknown>;
9
+ mcpSubmitOAuthCallbackUrl?(server: string, url: string): Promise<unknown>;
10
+ };
11
+
12
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
13
+
14
+ // Only a link a person can safely open: https, or http to this machine.
15
+ export function safeAuthUrl(value: unknown): string | null {
16
+ if (typeof value !== "string") return null;
17
+ try {
18
+ const url = new URL(value);
19
+ if (url.protocol === "https:") return url.href;
20
+ if (url.protocol === "http:" && LOOPBACK.has(url.hostname)) return url.href;
21
+ } catch {
22
+ // Not a URL.
23
+ }
24
+ return null;
25
+ }
26
+
27
+ // The CLI's answer to mcp_authenticate, as what the UI needs.
28
+ export function toSignInStart(
29
+ response: unknown
30
+ ): McpSignInStart & { state?: string } {
31
+ const r = (response ?? {}) as {
32
+ authUrl?: unknown;
33
+ requiresUserAction?: unknown;
34
+ callbackExpected?: unknown;
35
+ redirectScheme?: unknown;
36
+ state?: unknown;
37
+ };
38
+ if (!r.requiresUserAction && r.authUrl === undefined) return { mode: "done" };
39
+ const authUrl = safeAuthUrl(r.authUrl);
40
+ if (!authUrl)
41
+ throw new Error("The server gave a sign-in link AgentOS won't open");
42
+ if (!r.callbackExpected) return { mode: "external", authUrl };
43
+ const state = typeof r.state === "string" ? r.state : undefined;
44
+ return r.redirectScheme === "custom"
45
+ ? { mode: "callback", authUrl, state }
46
+ : { mode: "paste", authUrl, state };
47
+ }
48
+
49
+ // Whether a server can be signed in to: it speaks OAuth over HTTP.
50
+ export function canSignIn(s: McpServerStatus): boolean {
51
+ if (s.status !== "needs-auth") return false;
52
+ const c = s.config as { type?: string; command?: unknown } | undefined;
53
+ if (!c) return true;
54
+ return c.type === "http" || c.type === "sse" || c.type === "claudeai-proxy";
55
+ }
56
+
57
+ export function claudeMcpAuth(
58
+ q: Query,
59
+ view: (s: McpServerStatus) => McpServerView
60
+ ): McpAuth {
61
+ const auth = q as AuthQuery;
62
+ return {
63
+ async start(server, redirectUri) {
64
+ if (!auth.mcpAuthenticate)
65
+ throw new Error(
66
+ "This Claude Code version can't sign in to MCP servers from AgentOS"
67
+ );
68
+ return toSignInStart(await auth.mcpAuthenticate(server, redirectUri));
69
+ },
70
+ async submit(server, callbackUrl) {
71
+ if (!auth.mcpSubmitOAuthCallbackUrl)
72
+ throw new Error(
73
+ "This Claude Code version can't sign in to MCP servers from AgentOS"
74
+ );
75
+ await auth.mcpSubmitOAuthCallbackUrl(server, callbackUrl);
76
+ },
77
+ reconnect: (server) => q.reconnectMcpServer(server),
78
+ async servers() {
79
+ return (await q.mcpServerStatus()).map(view);
80
+ },
81
+ };
82
+ }
@@ -29,6 +29,7 @@ import { NO_ATTRIBUTION } from "../../agents/attribution";
29
29
  import { SUBAGENTS_ENV } from "../../models/subagent-env";
30
30
  import { parseSubagentEnv, subagentModelHook } from "../../models/subagents";
31
31
  import { callFromAssistant } from "../../usage/calls";
32
+ import { canSignIn, claudeMcpAuth } from "./claude-mcp-auth";
32
33
 
33
34
  // Claude Code through the Agent SDK, signed in with the user's own Claude
34
35
  // Code login. Asks for approval through chat cards unless given full access,
@@ -71,6 +72,10 @@ function cleanError(text?: string): string | undefined {
71
72
  return line.length > 300 ? `${line.slice(0, 299)}…` : line;
72
73
  }
73
74
 
75
+ export function cleanMcpError(text?: string): string | undefined {
76
+ return cleanError(text);
77
+ }
78
+
74
79
  export function mcpView(s: McpServerStatus): McpServerView {
75
80
  return {
76
81
  name: s.name,
@@ -78,6 +83,7 @@ export function mcpView(s: McpServerStatus): McpServerView {
78
83
  scope: s.source ?? s.scope,
79
84
  version: s.serverInfo?.version,
80
85
  error: cleanError(s.error),
86
+ ...(canSignIn(s) && { signIn: true }),
81
87
  tools: (s.tools ?? []).map((t) => ({
82
88
  name: t.name,
83
89
  description: firstLine(t.description),
@@ -346,6 +352,7 @@ export const claudeDriver: ChatDriver = {
346
352
  },
347
353
  ]);
348
354
  },
355
+ mcpAuth: claudeMcpAuth(q, mcpView),
349
356
  async interrupt() {
350
357
  await q.interrupt();
351
358
  },
@@ -104,9 +104,21 @@ export interface McpServerView {
104
104
  scope?: string;
105
105
  version?: string;
106
106
  error?: string;
107
+ // Needs sign-in and AgentOS can start it (the driver can, and the server
108
+ // speaks OAuth over HTTP). Decided by the server, never by its name.
109
+ signIn?: boolean;
107
110
  tools: { name: string; description?: string }[];
108
111
  }
109
112
 
113
+ // What starting an MCP server's sign-in came back with: "callback" (open the
114
+ // link; the provider returns to AgentOS), "paste" (the provider only returns
115
+ // to the machine running the session: paste the address it ends on),
116
+ // "external" (finish on claude.ai) or "done" (signed in without asking).
117
+ export interface McpSignInStart {
118
+ mode: "callback" | "paste" | "external" | "done";
119
+ authUrl?: string;
120
+ }
121
+
110
122
  // How full the conversation's context window is, as the agent last measured.
111
123
  export interface ChatContext {
112
124
  usedTokens: number;