Skip to content

Add connector update support and codemode utils - #89

Merged
kentcdodds merged 21 commits into
mainfrom
cursor/client-library-integration-in-dynamic-loader-6277
Mar 30, 2026
Merged

kentcdodds merged 21 commits into
mainfrom
cursor/client-library-integration-in-dynamic-loader-6277

Conversation

@kentcdodds

@kentcdodds kentcdodds commented Mar 29, 2026 •

Copy link
Copy Markdown
Member

Summary

  • add patch-style connector config updates with shared schema support for apiBaseUrl
  • expose @kody/codemode-utils to execute-time code and document the import pattern
  • wire the generated codemode sandbox bundle into the existing Nx worker targets and fix related typecheck issues
  • teach skill inference about helper-module capability usage and add focused tests

Testing

  • npm run typecheck
  • npm run test -- packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts packages/worker/src/mcp/skills/infer-codemode-capabilities.node.test.ts
  • npm run test:mcp -- packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts
Open in Web Open in Cursor 

Summary by CodeRabbit

  • New Features

    • Patch/update connector capability (connector_update) and optional connector apiBaseUrl; codemode utilities for token refresh + authenticated fetch; module capability mapping added
  • Tests

    • Added unit and e2e tests for connector updates, codemode utils, token refresh, authenticated fetch, and capability inference
  • Documentation

    • Execute tool and server docs updated to describe dynamic import/use of codemode helpers
  • Chores

    • Build/test scripts and Nx targets updated; sandbox module bundling and generated module file added; gitignore updated; CSS formatting tweak

Co-authored-by: me <me@kentcdodds.com>
@coderabbitai

coderabbitai Bot commented Mar 29, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Add codemode sandbox bundling and runtime helpers (refreshAccessToken, createAuthenticatedFetch), wire dynamic import capability inference and module manifest, introduce connector_update with apiBaseUrl and merge semantics, add generated-module build/test tooling, and include unit and MCP e2e tests.

Changes

Cohort / File(s) Summary
Workspace & scripts
package.json, nx.json, packages/worker/project.json
New root script build:codemode-sandbox-modules; switch root build/test scripts to Nx targets; add Nx target build-codemode-sandbox-modules with caching and target dependency wiring.
Bundler tool & generated artifact
tools/build-codemode-sandbox-modules.ts, packages/worker/src/mcp/generated/codemode-sandbox-modules.ts
Add esbuild-based script that bundles configured sandbox module specifiers and emits a generated TS file exporting codemodeSandboxModules.
Execute-time manifest & executor wiring
packages/worker/src/mcp/execute-modules/module-manifest.ts, packages/worker/src/mcp/executor.ts, packages/worker/src/mcp/index.ts
Add codemode module capability manifest and lookup helper; pass generated modules into DynamicWorkerExecutor; update server instruction text.
Codemode auth utilities
packages/worker/src/mcp/execute-modules/codemode-utils.ts, .../codemode-utils.node.test.ts
New runtime helpers: createCodemodeUtils, refreshAccessToken, createAuthenticatedFetch (handles refresh_token grant, secret placeholders, apiBaseUrl resolution); comprehensive unit tests.
Capability inference & skill persistence
packages/worker/src/mcp/skills/infer-codemode-capabilities.ts, .../infer-codemode-capabilities.node.test.ts, packages/worker/src/mcp/skills/skill-mutation.ts
Infer capabilities from dynamic import() module names (new moduleNames), include them when merging inferred capability names for persistence and tests updated.
Connector schema, update flow & tests
packages/worker/src/mcp/capabilities/values/connector-shared.ts, connector-update.ts, connector-update.node.test.ts, connector-save.ts, domain.ts
Add nullable apiBaseUrl to connector schema, add connectorUpdateSchema, mergeConnectorConfig, and a new connector_update capability with tests verifying patch semantics and legacy parsing.
Client & handler propagation
packages/worker/client/routes/connect-oauth.tsx, packages/worker/src/app/handlers/account-secrets.ts
Propagate optional apiBaseUrl from OAuth connect query through client session and into backend persistence during connect_oauth.
Execute tool docs & E2E test
packages/worker/src/mcp/tools/execute.ts, packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts
Document dynamic import usage of @kody/codemode-utils in execute examples; add MCP e2e test exercising connector setup and authenticated fetch attempt.
Tooling & config
tsconfig-tools.json, .gitignore
Include execute-modules sources in tools TS scope; ignore generated codemode-sandbox-modules.ts in git.
Styling reformat
packages/worker/public/mcp-apps/kody-ui-utils.css
Whitespace and selector formatting changes; single selector quoting change for data-kody-runtime.

Sequence Diagram

sequenceDiagram
    participant Dev as Sandbox Code
    participant Codemode as `@kody/codemode-utils`
    participant Store as Connector Storage
    participant Token as Token Server
    participant API as External API

    Dev->>Codemode: createCodemodeUtils(codemode)
    Codemode->>Store: connector_get('spotify')
    Store-->>Codemode: { tokenUrl, apiBaseUrl, flow, secretNames }
    Codemode->>Store: value_get(clientIdValueName)
    Store-->>Codemode: client_id
    Codemode->>Token: POST tokenUrl (form: grant_type=refresh_token + placeholders)
    Token-->>Codemode: { access_token }
    Codemode-->>Dev: returns authenticated fetch (adds Authorization)
    Dev->>API: GET /me/player (resolved against apiBaseUrl)
    API-->>Dev: response / error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Poem

🐰 I bundled bits in a cozy little mound,

Tokens refreshed and helpers scoped and bound,
Dynamic imports hop into play,
Relative paths find their way,
Hooray — the sandbox hums, the tests astound.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.88% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title "Add connector update support and codemode utils" clearly and concisely summarizes the main changes: adding connector update functionality and exposing codemode utilities.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cursor/client-library-integration-in-dynamic-loader-6277

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@kentcdodds
kentcdodds marked this pull request as ready for review March 29, 2026 15:10
@kentcdodds

Copy link
Copy Markdown
Member Author

@cursoragent should we use nx for managing build dependencies?

@cursor

cursor Bot commented Mar 29, 2026 •

Copy link
Copy Markdown
Contributor

Yes — for this repo, we should use Nx for managing this build dependency, and I’ve already wired it that way on the branch.

Why:

  • The new codemode sandbox bundle is a real worker build input/output, not just a convenience pre-step.
  • The repo already has a worker Nx project with build-oriented targets like build-client-web, build-mcp-apps, and build-client, so this fits the existing model naturally. project.json:1-97
  • Nx is the right place to declare:
    • the generated output
    • which worker targets depend on it
    • caching behavior

What I changed:

  • Added a dedicated worker Nx target for the generated sandbox module bundle and made the worker build/client targets depend on it. project.json:1-97
  • Added Nx target defaults so the new codemode sandbox build target is cached like the other worker build targets. nx.json:7-35
  • Kept the npm scripts too, but now they align with the Nx model instead of being the only dependency mechanism. package.json:23-62
  • Kept the generator as a normal tools script that emits the generated module map consumed by the worker executor. build-codemode-sandbox-modules.ts:1-70 codemode-sandbox-modules.ts:1-15 executor.ts:19-38

So my recommendation is:

  • Use Nx to manage the dependency graph and outputs.
  • Keep the script as the implementation detail of that target.
  • Avoid relying only on ad-hoc npm run ... && ... chaining for something that is now part of the worker build graph.

I also fixed the related typecheck/runtime issues so this isn’t just a theoretical recommendation; it’s implemented and validated on the PR branch at 838969a.

Testing

  • ✅ npm run typecheck
  • ✅ npm run test -- packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts packages/worker/src/mcp/skills/infer-codemode-capabilities.node.test.ts
  • ✅ npm run test:mcp -- packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts

One note: there’s still an unrelated uncommitted formatting-only drift in packages/worker/public/mcp-apps/kody-ui-utils.css from the existing MCP app build step, and I left that out of the commits on purpose.

Open in Web Open in Cursor 

@github-actions

github-actions Bot commented Mar 29, 2026 •

Copy link
Copy Markdown
Contributor

🔎 Preview deployed: https://kody-pr-89.kentcdodds.workers.dev

Worker: kody-pr-89
D1: kody-pr-89-db
KV: kody-pr-89-oauth-kv

Mocks:

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/worker/src/mcp/executor.ts (1)

30-37: ⚠️ Potential issue | 🔴 Critical

Fix modules payload type mismatch in executor wiring.

Line 36 passes Record<string, { js: string }> to an API expecting Record<string, string>. Extract the js property from each module object to match the DynamicWorkerExecutor API contract.

Proposed fix
 import { codemodeSandboxModules } from '#mcp/generated/codemode-sandbox-modules.ts'
+
+const codemodeSandboxModuleSources = Object.fromEntries(
+	Object.entries(codemodeSandboxModules).map(([specifier, module]) => [
+		specifier,
+		module.js,
+	]),
+) as Record<string, string>
 
 export function createExecuteExecutor(input: {
 	env: Env
 	exports?: WorkerLoopbackExports
 	gatewayProps: FetchGatewayProps
@@
 	return new DynamicWorkerExecutor({
 		loader: input.env.LOADER,
 		timeout: 90_000,
 		globalOutbound: loopbackExports.CodemodeFetchGateway({
 			props: input.gatewayProps,
 		}),
-		modules: codemodeSandboxModules,
+		modules: codemodeSandboxModuleSources,
 	})
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/src/mcp/executor.ts` around lines 30 - 37, The modules prop
passed to DynamicWorkerExecutor currently supplies Record<string, { js: string
}>, causing a type mismatch; transform codemodeSandboxModules into
Record<string, string> by mapping over its entries and replacing each module
object with its .js string before creating the executor. Update the
DynamicWorkerExecutor call (modules: ...) to produce the mapped object
(extracting module.js for each key) so the modules argument matches the executor
API.
🧹 Nitpick comments (2)
packages/worker/src/mcp/capabilities/values/connector-shared.ts (1)

52-61: Minor: Redundant trim() call on update.name.

The normalizeConnectorConfig function already trims name on line 41, so the explicit update.name.trim() on line 59 is redundant.

♻️ Optional simplification
 export function mergeConnectorConfig(
 	current: ConnectorConfig,
 	update: ConnectorUpdate,
 ): ConnectorConfig {
 	return normalizeConnectorConfig({
 		...current,
 		...update,
-		name: update.name.trim(),
 	})
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/src/mcp/capabilities/values/connector-shared.ts` around lines
52 - 61, In mergeConnectorConfig, remove the redundant explicit trim of
update.name and let normalizeConnectorConfig perform the trimming; update the
return to spread current and update and either omit the name override entirely
or use name: update.name (without .trim()), referencing the mergeConnectorConfig
function and normalizeConnectorConfig to locate the change.
packages/worker/src/mcp/execute-modules/codemode-utils.ts (1)

167-172: Dead code: Request.url is always an absolute URL.

When a Request is constructed, its url property is normalized to an absolute URL string. The condition input.url.startsWith('/') will never be true, making this branch unreachable.

♻️ Proposed fix: remove dead branch
 function resolveRequestUrl(input: RequestInfo | URL, connector: ConnectorConfig) {
 	if (typeof input === 'string' && input.startsWith('/')) {
 		return resolveRelativeUrl(input, connector)
 	}
 	if (input instanceof URL) return input
 	if (typeof input === 'string') return input
-	if (input instanceof Request && input.url.startsWith('/')) {
-		return new Request(
-			resolveRelativeUrl(input.url, connector),
-			input,
-		)
-	}
 	return input
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/src/mcp/execute-modules/codemode-utils.ts` around lines 167 -
172, The branch checking Request.url startsWith('/') is dead because Request.url
is always absolute; remove the entire conditional that tests "if (input
instanceof Request && input.url.startsWith('/')) { ... }" in codemode-utils.ts
and instead let other code paths handle Request inputs (keep the
resolveRelativeUrl and Request usage only where needed); ensure any callers
expecting a rewritten Request still work by consolidating logic to the existing
absolute-URL handling so there are no dangling references to
input.url.startsWith or this conditional.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/worker/src/mcp/capabilities/values/connector-update.ts`:
- Around line 66-75: The update currently allows renaming connectors which
orphan the old value; to fix this, make connector name immutable by updating
connectorUpdateSchema to disallow/mark name as immutable and in the update flow
(around mergeConnectorConfig and before calling
saveValue/buildConnectorValueName) enforce the original name by overriding
args.name/connector.name with current.name (or throw a validation error if they
differ) so the saved key remains buildConnectorValueName(current.name); this
avoids creating an orphaned `_connector:<old>` entry.

In `@packages/worker/src/mcp/execute-modules/codemode-utils.ts`:
- Around line 142-155: The TypeScript error arises because codemode.value_get
may be undefined before it's called in readClientId; update the readClientId
function to first verify that codemode.value_get exists (and is callable) and
throw a clear error if it's missing, then call it and keep the existing check
for value?.value (using the same ValueGetResult and connector.clientIdValueName
references); alternatively explicitly narrow the type (e.g., guard or type
assertion) so the compiler knows value_get is present before invoking it.
- Around line 128-140: The TypeScript error occurs because codemode is typed as
Record and codemode.connector_get may be undefined; in readConnectorConfig you
should guard or refine the type before calling it: check that
codemode.connector_get is present and is a function (e.g., if (typeof
codemode.connector_get !== 'function') throw new Error(...)) or narrow
CodemodeNamespace so connector_get is required, then call
codemode.connector_get({ name: providerName }) and handle the case where the
call itself returns undefined (validate result?.connector and throw a clear
error referencing providerName and ConnectorGetResult). Ensure you reference the
readConnectorConfig function, CodemodeNamespace, connector_get, and
ConnectorGetResult when applying the fix.

In `@packages/worker/src/mcp/execute-modules/module-manifest.ts`:
- Around line 5-7: The function getCodemodeModuleCapabilities cannot index
codemodeModuleCapabilityManifest because the manifest is narrowed with `as
const`; update the function to either accept/return a broader type and safely
access the manifest: change the return type to ReadonlyArray<string> and perform
a runtime key check (`if (specifier in codemodeModuleCapabilityManifest)`) then
index using `specifier as keyof typeof codemodeModuleCapabilityManifest`,
otherwise return []; alternatively, cast codemodeModuleCapabilityManifest to
Record<string, ReadonlyArray<string>> before indexing to satisfy TypeScript.
Ensure references to getCodemodeModuleCapabilities and
codemodeModuleCapabilityManifest are updated accordingly.

In `@packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts`:
- Around line 837-841: The local variable `structuredResult` in the test is
declared but never used; remove the unused declaration `(result as
CallToolResult).structuredContent as { result?: Record<string, unknown> } |
undefined` (or replace it with a named-ignored binding like `_structuredResult`
if you prefer an explicit ignore) so the test no longer has an unused variable
(`structuredResult`) and the static-analysis warning is resolved.

---

Outside diff comments:
In `@packages/worker/src/mcp/executor.ts`:
- Around line 30-37: The modules prop passed to DynamicWorkerExecutor currently
supplies Record<string, { js: string }>, causing a type mismatch; transform
codemodeSandboxModules into Record<string, string> by mapping over its entries
and replacing each module object with its .js string before creating the
executor. Update the DynamicWorkerExecutor call (modules: ...) to produce the
mapped object (extracting module.js for each key) so the modules argument
matches the executor API.

---

Nitpick comments:
In `@packages/worker/src/mcp/capabilities/values/connector-shared.ts`:
- Around line 52-61: In mergeConnectorConfig, remove the redundant explicit trim
of update.name and let normalizeConnectorConfig perform the trimming; update the
return to spread current and update and either omit the name override entirely
or use name: update.name (without .trim()), referencing the mergeConnectorConfig
function and normalizeConnectorConfig to locate the change.

In `@packages/worker/src/mcp/execute-modules/codemode-utils.ts`:
- Around line 167-172: The branch checking Request.url startsWith('/') is dead
because Request.url is always absolute; remove the entire conditional that tests
"if (input instanceof Request && input.url.startsWith('/')) { ... }" in
codemode-utils.ts and instead let other code paths handle Request inputs (keep
the resolveRelativeUrl and Request usage only where needed); ensure any callers
expecting a rewritten Request still work by consolidating logic to the existing
absolute-URL handling so there are no dangling references to
input.url.startsWith or this conditional.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 95c14612-b883-4942-883e-539d66e80411

📥 Commits

Reviewing files that changed from the base of the PR and between 242d2b9 and d1f3ab8.

⛔ Files ignored due to path filters (1)
  • packages/worker/src/mcp/generated/codemode-sandbox-modules.ts is excluded by !**/generated/**
📒 Files selected for processing (19)
  • package.json
  • packages/worker/client/routes/connect-oauth.tsx
  • packages/worker/src/app/handlers/account-secrets.ts
  • packages/worker/src/mcp/capabilities/values/connector-save.ts
  • packages/worker/src/mcp/capabilities/values/connector-shared.ts
  • packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts
  • packages/worker/src/mcp/capabilities/values/connector-update.ts
  • packages/worker/src/mcp/capabilities/values/domain.ts
  • packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
  • packages/worker/src/mcp/execute-modules/codemode-utils.ts
  • packages/worker/src/mcp/execute-modules/module-manifest.ts
  • packages/worker/src/mcp/executor.ts
  • packages/worker/src/mcp/index.ts
  • packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts
  • packages/worker/src/mcp/skills/infer-codemode-capabilities.node.test.ts
  • packages/worker/src/mcp/skills/infer-codemode-capabilities.ts
  • packages/worker/src/mcp/skills/skill-mutation.ts
  • packages/worker/src/mcp/tools/execute.ts
  • tools/build-codemode-sandbox-modules.ts

Comment on lines +66 to +75
const connector = mergeConnectorConfig(current, args)
const value = await saveValue({
env: ctx.env,
userId: user.userId,
name: buildConnectorValueName(connector.name),
value: JSON.stringify(connector),
scope: 'user',
description: `OAuth connector config for ${connector.name}`,
storageContext,
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if connectorUpdateSchema allows updating the 'name' field
ast-grep --pattern $'connectorUpdateSchema = $_'

# Also check mergeConnectorConfig implementation
ast-grep --pattern $'function mergeConnectorConfig($_, $_) {
  $$$
}'

Repository: kentcdodds/kody

Length of output: 41


🏁 Script executed:

#!/bin/bash
# Check if the file exists
ls -la packages/worker/src/mcp/capabilities/values/connector-update.ts 2>/dev/null || echo "File not found"

# List files in the directory to understand structure
find packages/worker/src/mcp/capabilities/values -type f -name "*.ts" 2>/dev/null | head -20

Repository: kentcdodds/kody

Length of output: 962


🏁 Script executed:

#!/bin/bash
# Read the connector-update.ts file
cat -n packages/worker/src/mcp/capabilities/values/connector-update.ts

Repository: kentcdodds/kody

Length of output: 3035


🏁 Script executed:

#!/bin/bash
# Read connector-shared.ts to check the schema and merge function
cat -n packages/worker/src/mcp/capabilities/values/connector-shared.ts

Repository: kentcdodds/kody

Length of output: 3792


🏁 Script executed:

#!/bin/bash
# Check the test file to understand intended behavior
cat -n packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts

Repository: kentcdodds/kody

Length of output: 6336


🏁 Script executed:

#!/bin/bash
# Check connector-save to see if it has similar pattern
head -n 100 packages/worker/src/mcp/capabilities/values/connector-save.ts

Repository: kentcdodds/kody

Length of output: 1887


🏁 Script executed:

#!/bin/bash
# Check if there's any validation or comments about name field semantics in the codebase
rg -A 5 -B 5 "connectorUpdateSchema" packages/worker/src/mcp/capabilities/values/ --type ts

Repository: kentcdodds/kody

Length of output: 3625


🏁 Script executed:

#!/bin/bash
# Check if there's any documentation or discussion about connector name mutability
rg "name.*immut|immut.*name|connector.*rename|rename.*connector" packages/worker/src/mcp/capabilities/values/ --type ts -i

Repository: kentcdodds/kody

Length of output: 41


🏁 Script executed:

#!/bin/bash
# Check the description and comments around connector_update more carefully
sed -n '22,40p' packages/worker/src/mcp/capabilities/values/connector-update.ts

# Also check if there are any related issues or discussions in comments
rg "TODO|FIXME|BUG|XXX" packages/worker/src/mcp/capabilities/values/connector-update.ts

Repository: kentcdodds/kody

Length of output: 504


Connector name changes will create orphaned values.

The connectorUpdateSchema allows name to be changed (it's a required field, not marked immutable). If an update includes a different name, the code will save under the new name while leaving the old value orphaned.

For example:

  • Retrieves existing _connector:spotify (line 52)
  • Merges with update containing name: 'apple-music' (line 66)
  • Saves as _connector:apple-music (line 70)
  • _connector:spotify is left orphaned

Either disallow name changes in the schema or implement cleanup of the old value when the name changes. The description states "Update...by name," suggesting name should be the lookup key, not an editable field.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/src/mcp/capabilities/values/connector-update.ts` around lines
66 - 75, The update currently allows renaming connectors which orphan the old
value; to fix this, make connector name immutable by updating
connectorUpdateSchema to disallow/mark name as immutable and in the update flow
(around mergeConnectorConfig and before calling
saveValue/buildConnectorValueName) enforce the original name by overriding
args.name/connector.name with current.name (or throw a validation error if they
differ) so the saved key remains buildConnectorValueName(current.name); this
avoids creating an orphaned `_connector:<old>` entry.

Co-authored-by: me <me@kentcdodds.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
packages/worker/src/mcp/execute-modules/codemode-utils.ts (1)

177-182: Request URL check on line 177 is unreachable dead code.

Per the WHATWG Fetch specification, Request.url is always an absolute URL string. When a Request is constructed with a relative path (e.g., new Request('/path')), it's resolved against the current origin, resulting in an absolute URL starting with the protocol (http:// or https://). The condition input.url.startsWith('/') can never be true, making lines 177-182 unreachable.

Consider removing this branch or adding a comment if it's intentionally defensive.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/src/mcp/execute-modules/codemode-utils.ts` around lines 177 -
182, The branch that checks input instanceof Request and
input.url.startsWith('/') is dead because Request.url is always absolute per the
WHATWG spec; remove the entire conditional that attempts to re-create the
Request using resolveRelativeUrl(connector) (the code using input instanceof
Request, input.url.startsWith('/'), new Request(...), and resolveRelativeUrl)
or, if you want to keep it for clarity, replace it with a short defensive
comment explaining why it is unreachable; ensure any callers relying on that
branch still work and no duplicate Request construction remains.
packages/worker/project.json (2)

13-21: Add explicit target inputs to prevent Nx cache misses when the generator script changes.

This target generates a runtime artifact via tools/build-codemode-sandbox-modules.ts and has caching enabled via targetDefaults, but no explicit inputs are declared. If that script is modified, Nx will serve stale cached output because the generator is not part of the target's cache hash.

Proposed diff
 		"build-codemode-sandbox-modules": {
 			"executor": "nx:run-commands",
+			"inputs": [
+				"default",
+				"{workspaceRoot}/tools/build-codemode-sandbox-modules.ts"
+			],
 			"outputs": [
 				"{workspaceRoot}/packages/worker/src/mcp/generated/codemode-sandbox-modules.ts"
 			],
 			"options": {
 				"command": "npm run build:codemode-sandbox-modules"
 			}
 		},
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/project.json` around lines 13 - 21, The target
"build-codemode-sandbox-modules" is missing explicit "inputs" so changes to the
generator script aren't hashed; add an "inputs" entry for this target that
includes the standard default inputs plus the generator script (e.g.,
"tools/build-codemode-sandbox-modules.ts") and any files that affect the build
(package.json/package-lock.json or scripts if relevant) so Nx will invalidate
cache when those change; update the "build-codemode-sandbox-modules" target in
project.json to include an "inputs": ["default",
"tools/build-codemode-sandbox-modules.ts", "package.json", "package-lock.json"]
(or equivalent files used by the script).

53-65: Dependency ordering is good; build.dependsOn can be simplified.

Line 53 already makes build-client depend on build-codemode-sandbox-modules. Since Nx executes dependsOn transitively, Line 65 can keep only build-client to avoid a redundant edge.

Optional cleanup
 		"build": {
 			"executor": "nx:run-commands",
-			"dependsOn": ["build-codemode-sandbox-modules", "build-client"],
+			"dependsOn": ["build-client"],
 			"options": {
 				"command": "npm run build"
 			}
 		},
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/project.json` around lines 53 - 65, The build target's
dependsOn array contains a redundant explicit reference to
build-codemode-sandbox-modules; remove "build-codemode-sandbox-modules" from the
"build".dependsOn so it only lists "build-client" (since build-client already
depends on build-codemode-sandbox-modules transitively). Update the JSON for the
"build" target's "dependsOn" to keep only "build-client" to simplify the
dependency graph.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/worker/project.json`:
- Around line 13-21: The target "build-codemode-sandbox-modules" is missing
explicit "inputs" so changes to the generator script aren't hashed; add an
"inputs" entry for this target that includes the standard default inputs plus
the generator script (e.g., "tools/build-codemode-sandbox-modules.ts") and any
files that affect the build (package.json/package-lock.json or scripts if
relevant) so Nx will invalidate cache when those change; update the
"build-codemode-sandbox-modules" target in project.json to include an "inputs":
["default", "tools/build-codemode-sandbox-modules.ts", "package.json",
"package-lock.json"] (or equivalent files used by the script).
- Around line 53-65: The build target's dependsOn array contains a redundant
explicit reference to build-codemode-sandbox-modules; remove
"build-codemode-sandbox-modules" from the "build".dependsOn so it only lists
"build-client" (since build-client already depends on
build-codemode-sandbox-modules transitively). Update the JSON for the "build"
target's "dependsOn" to keep only "build-client" to simplify the dependency
graph.

In `@packages/worker/src/mcp/execute-modules/codemode-utils.ts`:
- Around line 177-182: The branch that checks input instanceof Request and
input.url.startsWith('/') is dead because Request.url is always absolute per the
WHATWG spec; remove the entire conditional that attempts to re-create the
Request using resolveRelativeUrl(connector) (the code using input instanceof
Request, input.url.startsWith('/'), new Request(...), and resolveRelativeUrl)
or, if you want to keep it for clarity, replace it with a short defensive
comment explaining why it is unreachable; ensure any callers relying on that
branch still work and no duplicate Request construction remains.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ab22c55b-7830-4b32-b0a6-00072c94116d

📥 Commits

Reviewing files that changed from the base of the PR and between d1f3ab8 and 838969a.

⛔ Files ignored due to path filters (1)
  • packages/worker/src/mcp/generated/codemode-sandbox-modules.ts is excluded by !**/generated/**
📒 Files selected for processing (9)
  • nx.json
  • packages/worker/project.json
  • packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
  • packages/worker/src/mcp/execute-modules/codemode-utils.ts
  • packages/worker/src/mcp/execute-modules/module-manifest.ts
  • packages/worker/src/mcp/executor.ts
  • packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts
  • packages/worker/src/mcp/skills/infer-codemode-capabilities.ts
  • tsconfig-tools.json
✅ Files skipped from review due to trivial changes (4)
  • tsconfig-tools.json
  • nx.json
  • packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts
  • packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/worker/src/mcp/executor.ts
  • packages/worker/src/mcp/skills/infer-codemode-capabilities.ts
  • packages/worker/src/mcp/execute-modules/module-manifest.ts

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 2 total unresolved issues (including 1 from previous review).

Autofix Details

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Generated codemodeSandboxModuleManifest export is never imported
    • Removed the unused generated manifest export from the build script and generated output so only the sandbox module bundle remains.

cursoragent and others added 2 commits March 29, 2026 15:27
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
@cursor

This comment has been minimized.

@kentcdodds

Copy link
Copy Markdown
Member Author

@cursoragent i like your recommendation and please check on the CI typescript failure

@cursor

This comment has been minimized.

cursoragent and others added 4 commits March 29, 2026 15:50
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: me <me@kentcdodds.com>
Co-authored-by: me <me@kentcdodds.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/worker/src/mcp/execute-modules/codemode-utils.ts (1)

167-176: Consider including error details from OAuth error responses.

OAuth token endpoints typically return structured error information (e.g., error, error_description) in the response body. Since payload is already parsed before this check, including it in the error message would aid debugging.

♻️ Suggested improvement
 	if (!response.ok) {
+		const errorDetail = payload?.error_description ?? payload?.error ?? ''
+		const suffix = errorDetail ? ` Error: ${errorDetail}` : ''
 		throw new Error(
-			`Token refresh failed for connector "${providerName}" with HTTP ${response.status}.`,
+			`Token refresh failed for connector "${providerName}" with HTTP ${response.status}.${suffix}`,
 		)
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/src/mcp/execute-modules/codemode-utils.ts` around lines 167 -
176, The error handling around the OAuth token refresh should include the parsed
error details to aid debugging; update the throws in the block that checks
response.ok and payload.access_token (variables: response, payload,
providerName) to append the response payload (and response.status) to the Error
message so the thrown errors include structured OAuth fields like error and
error_description returned by the token endpoint.
tools/build-codemode-sandbox-modules.ts (1)

21-29: Consider using a less restrictive log level.

logLevel: 'silent' suppresses all esbuild output, including warnings about unresolved imports, deprecated syntax, or other potential issues in the bundled code. This could hide problems that affect runtime behavior in the sandbox.

♻️ Suggested change
 const result = await build({
 	entryPoints: [entryPoint],
 	bundle: true,
 	format: 'esm',
 	platform: 'browser',
 	target: 'es2022',
 	write: false,
-	logLevel: 'silent',
+	logLevel: 'warning',
 })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tools/build-codemode-sandbox-modules.ts` around lines 21 - 29, The esbuild
invocation using build(...) currently sets logLevel: 'silent', which hides
warnings and useful messages; update the build call (the build({ entryPoints,
bundle, format, platform, target, write, logLevel }) invocation) to use a less
restrictive log level such as 'warn' or 'info' instead of 'silent' so that
unresolved imports and other warnings are surfaced during bundling; ensure only
the logLevel property is changed and keep other options (bundle, format,
platform, target, write) intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tools/build-codemode-sandbox-modules.ts`:
- Around line 43-54: The generated codemodeSandboxModules currently produces
Record<string, { js: string }>, but DynamicWorkerExecutorOptions['modules']
expects Record<string, string>; fix by making codemodeSandboxModules export raw
source strings (Record<string, string>) or, alternatively, update the call site
where codemodeSandboxModules is passed to the executor (currently cast with "as
unknown as" in executor.ts) to map/unpack each value to its .js string before
constructing DynamicWorkerExecutorOptions.modules; locate the generator symbol
codemodeSandboxModules and the consumer in executor.ts (the "as unknown as"
cast) and implement one of these two fixes so types align without unsafe
casting.

---

Nitpick comments:
In `@packages/worker/src/mcp/execute-modules/codemode-utils.ts`:
- Around line 167-176: The error handling around the OAuth token refresh should
include the parsed error details to aid debugging; update the throws in the
block that checks response.ok and payload.access_token (variables: response,
payload, providerName) to append the response payload (and response.status) to
the Error message so the thrown errors include structured OAuth fields like
error and error_description returned by the token endpoint.

In `@tools/build-codemode-sandbox-modules.ts`:
- Around line 21-29: The esbuild invocation using build(...) currently sets
logLevel: 'silent', which hides warnings and useful messages; update the build
call (the build({ entryPoints, bundle, format, platform, target, write, logLevel
}) invocation) to use a less restrictive log level such as 'warn' or 'info'
instead of 'silent' so that unresolved imports and other warnings are surfaced
during bundling; ensure only the logLevel property is changed and keep other
options (bundle, format, platform, target, write) intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 869511e2-f427-4f80-b3d0-5ea31d5933f7

📥 Commits

Reviewing files that changed from the base of the PR and between 838969a and c60ce1f.

⛔ Files ignored due to path filters (1)
  • packages/worker/src/mcp/generated/codemode-sandbox-modules.ts is excluded by !**/generated/**
📒 Files selected for processing (7)
  • packages/worker/project.json
  • packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts
  • packages/worker/src/mcp/capabilities/values/connector-update.ts
  • packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
  • packages/worker/src/mcp/execute-modules/codemode-utils.ts
  • packages/worker/src/mcp/execute-modules/module-manifest.ts
  • tools/build-codemode-sandbox-modules.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
  • packages/worker/project.json
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/worker/src/mcp/execute-modules/module-manifest.ts
  • packages/worker/src/mcp/capabilities/values/connector-update.ts
  • packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts

Comment thread tools/build-codemode-sandbox-modules.ts Resolved
Comment thread package.json Outdated
"test:e2e:ui": "playwright test --ui",
"test:e2e:install": "playwright install chromium --with-deps",
"test:mcp": "node tools/prepare-e2e-env.ts && npm run build:mcp-apps && vitest run --project mcp-e2e",
"test:mcp": "node tools/prepare-e2e-env.ts && npm run build:codemode-sandbox-modules && npm run build:mcp-apps && vitest run --project mcp-e2e",

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cursoragent, can we not use nx to manage these script dependencies? That way we don't have to build unnecessarily (can rely on cache) and we don't have to keep updating this.

Applies to test and build above as well I think.

@cursor cursor Bot Mar 29, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Relative URL resolution silently skipped for Request inputs
    • Requests constructed with a runtime-origin URL now get their path resolved against apiBaseUrl while already-resolved connector URLs stay untouched.
  • ✅ Fixed: Connector update lookup uses raw but saves normalized name
    • The update handler now trims the connector name before lookup and error reporting to ensure the read and write keys match.

Create PR

Preview (b14dc874b4)
diff --git a/nx.json b/nx.json
--- a/nx.json
+++ b/nx.json
@@ -8,6 +8,9 @@
 		"build": {
 			"cache": true
 		},
+		"build-codemode-sandbox-modules": {
+			"cache": true
+		},
 		"build-client": {
 			"cache": true
 		},

diff --git a/package.json b/package.json
--- a/package.json
+++ b/package.json
@@ -22,6 +22,7 @@
   },
   "scripts": {
     "dev": "node --env-file=packages/worker/.env cli.ts",
+    "build:codemode-sandbox-modules": "node tools/build-codemode-sandbox-modules.ts",
     "dev:home-connector": "npm --prefix packages/home-connector run dev",
     "dev:client": "concurrently --kill-others-on-fail -n web,mcp-apps -c green,cyan \"npm run dev:client:web\" \"npm run dev:mcp-apps\"",
     "dev:client:web": "esbuild packages/worker/client/entry.tsx --bundle --format=esm --target=es2022 --outdir=packages/worker/public --entry-names=client-entry --chunk-names=assets/[name] --asset-names=assets/[name] --jsx=automatic --jsx-import-source=remix/component --watch",
@@ -37,7 +38,7 @@
     "build:mcp-apps": "esbuild packages/worker/client/mcp-apps/kody-ui-utils.ts --bundle --format=esm --target=es2022 --outfile=packages/worker/public/mcp-apps/kody-ui-utils.js --platform=browser --banner:js='/* eslint-disable no-undef */'",
     "build:client:web": "esbuild packages/worker/client/entry.tsx --bundle --format=esm --target=es2022 --outdir=packages/worker/public --entry-names=client-entry --chunk-names=assets/[name] --asset-names=assets/[name] --jsx=automatic --jsx-import-source=remix/component",
     "build:client": "npm run build:client:web && npm run build:mcp-apps",
-    "build": "npm run build:client && node --env-file=packages/worker/.env ./wrangler-env.ts build",
+    "build": "npm run build:codemode-sandbox-modules && npm run build:client && node --env-file=packages/worker/.env ./wrangler-env.ts build",
     "lint": "oxlint .",
     "lint:fix": "oxlint . --fix",
     "format": "oxfmt",
@@ -48,13 +49,13 @@
     "preview:e2e": "node --env-file=packages/worker/.env tools/prepare-e2e-env.ts && npx nx run worker:build-client && npm run migrate:e2e && node --env-file=packages/worker/.env ./wrangler-env.ts dev --local --persist-to .wrangler/state/e2e",
     "generate-types": "node --env-file=packages/worker/.env ./wrangler-env.ts types ./packages/worker/worker-configuration.d.ts",
     "typecheck": "tsc -b --noEmit",
-    "test": "vitest run --project node-unit --project workers-unit",
+    "test": "npm run build:codemode-sandbox-modules && vitest run --project node-unit --project workers-unit",
     "inspect": "npx -y @mcpjam/inspector inspector",
     "validate": "concurrently --kill-others-on-fail -n format,lint,build,typecheck,test,test:mcp -c green,yellow,blue,magenta,cyan,red \"npm run format:check\" \"npm run lint:fix\" \"npm run build\" \"npm run typecheck\" \"npm run test:e2e\" \"npm run test:mcp\"",
     "test:e2e": "playwright test",
     "test:e2e:ui": "playwright test --ui",
     "test:e2e:install": "playwright install chromium --with-deps",
-    "test:mcp": "node tools/prepare-e2e-env.ts && npm run build:mcp-apps && vitest run --project mcp-e2e",
+    "test:mcp": "node tools/prepare-e2e-env.ts && npm run build:codemode-sandbox-modules && npm run build:mcp-apps && vitest run --project mcp-e2e",
     "prepare": "husky",
     "nx:graph": "nx graph",
     "nx:show-projects": "nx show projects"

diff --git a/packages/worker/client/routes/connect-oauth.tsx b/packages/worker/client/routes/connect-oauth.tsx
--- a/packages/worker/client/routes/connect-oauth.tsx
+++ b/packages/worker/client/routes/connect-oauth.tsx
@@ -10,6 +10,7 @@
 	tokenHost: string
 	authorizeUrl: string
 	tokenUrl: string
+	apiBaseUrl: string | null
 	scopes: Array<string>
 	flow: OAuthFlow
 	scopeSeparator: string
@@ -93,6 +94,7 @@
 		const provider = readRequired('provider')
 		const authorizeUrl = readRequired('authorizeUrl')
 		const tokenUrl = readRequired('tokenUrl')
+		const apiBaseUrl = parseOptionalUrl(readOptional('apiBaseUrl'))
 		if (!provider || !authorizeUrl || !tokenUrl) {
 			hasConfigError = true
 			setStatus('Missing required OAuth configuration parameters.', 'error')
@@ -138,6 +140,7 @@
 			tokenHost,
 			authorizeUrl,
 			tokenUrl,
+			apiBaseUrl,
 			scopes,
 			flow: flow as OAuthFlow,
 			scopeSeparator,
@@ -521,6 +524,7 @@
 				provider: config.provider,
 				callbackUrl,
 				tokenUrl: config.tokenUrl,
+				apiBaseUrl: config.apiBaseUrl,
 				flow: config.flow,
 				clientIdValueName: config.clientIdValueName,
 				clientSecretSecretName: config.clientSecretSecretName,

diff --git a/packages/worker/project.json b/packages/worker/project.json
--- a/packages/worker/project.json
+++ b/packages/worker/project.json
@@ -10,6 +10,21 @@
 				"command": "npm run dev"
 			}
 		},
+		"build-codemode-sandbox-modules": {
+			"executor": "nx:run-commands",
+			"inputs": [
+				"default",
+				"{workspaceRoot}/tools/build-codemode-sandbox-modules.ts",
+				"{workspaceRoot}/package.json",
+				"{workspaceRoot}/package-lock.json"
+			],
+			"outputs": [
+				"{workspaceRoot}/packages/worker/src/mcp/generated/codemode-sandbox-modules.ts"
+			],
+			"options": {
+				"command": "npm run build:codemode-sandbox-modules"
+			}
+		},
 		"dev-client": {
 			"executor": "nx:run-commands",
 			"options": {
@@ -41,6 +56,7 @@
 		},
 		"build-client": {
 			"executor": "nx:run-commands",
+			"dependsOn": ["build-codemode-sandbox-modules"],
 			"outputs": [
 				"{workspaceRoot}/packages/worker/public/client-entry.js",
 				"{workspaceRoot}/packages/worker/public/assets",
@@ -52,6 +68,7 @@
 		},
 		"build": {
 			"executor": "nx:run-commands",
+			"dependsOn": ["build-client"],
 			"options": {
 				"command": "npm run build"
 			}

diff --git a/packages/worker/src/app/handlers/account-secrets.ts b/packages/worker/src/app/handlers/account-secrets.ts
--- a/packages/worker/src/app/handlers/account-secrets.ts
+++ b/packages/worker/src/app/handlers/account-secrets.ts
@@ -237,6 +237,7 @@
 }) {
 	const provider = readString(input.body, 'provider')
 	const tokenUrl = readOptionalString(input.body, 'tokenUrl')
+	const apiBaseUrl = readOptionalString(input.body, 'apiBaseUrl')
 	const flow = readOptionalString(input.body, 'flow')
 	const clientIdValueName = readOptionalString(input.body, 'clientIdValueName')
 	const clientSecretSecretName = readOptionalString(
@@ -345,6 +346,7 @@
 		userId: input.user.mcpUser.userId,
 		provider,
 		tokenUrl,
+		apiBaseUrl,
 		flow: flow === 'confidential' ? 'confidential' : 'pkce',
 		clientIdValueName,
 		clientSecretSecretName,
@@ -449,6 +451,7 @@
 	userId: string
 	provider: string
 	tokenUrl: string
+	apiBaseUrl: string | null
 	flow: 'pkce' | 'confidential'
 	clientIdValueName: string
 	clientSecretSecretName: string | null
@@ -464,6 +467,7 @@
 	const connector = normalizeConnectorConfig({
 		name: input.provider,
 		tokenUrl: input.tokenUrl,
+		apiBaseUrl: input.apiBaseUrl,
 		flow: input.flow,
 		clientIdValueName: input.clientIdValueName,
 		clientSecretSecretName:

diff --git a/packages/worker/src/mcp/capabilities/values/connector-save.ts b/packages/worker/src/mcp/capabilities/values/connector-save.ts
--- a/packages/worker/src/mcp/capabilities/values/connector-save.ts
+++ b/packages/worker/src/mcp/capabilities/values/connector-save.ts
@@ -23,7 +23,7 @@
 	{
 		name: 'connector_save',
 		description:
-			'Save an OAuth connector configuration for the signed-in user. Stored as a user-scoped value with a _connector: prefix.',
+			'Save or replace an OAuth connector configuration for the signed-in user. Stored as a user-scoped value with a _connector: prefix.',
 		keywords: ['connector', 'oauth', 'config', 'registry', 'save', 'value'],
 		readOnly: false,
 		idempotent: false,

diff --git a/packages/worker/src/mcp/capabilities/values/connector-shared.ts b/packages/worker/src/mcp/capabilities/values/connector-shared.ts
--- a/packages/worker/src/mcp/capabilities/values/connector-shared.ts
+++ b/packages/worker/src/mcp/capabilities/values/connector-shared.ts
@@ -6,6 +6,7 @@
 export const connectorConfigSchema = z.object({
 	name: z.string().min(1),
 	tokenUrl: z.string().url(),
+	apiBaseUrl: z.string().url().optional().nullable(),
 	flow: z.enum(connectorFlowValues),
 	clientIdValueName: z.string().min(1),
 	clientSecretSecretName: z.string().min(1).optional().nullable(),
@@ -16,6 +17,22 @@
 
 export type ConnectorConfig = z.infer<typeof connectorConfigSchema>
 
+export const connectorUpdateSchema = z
+	.object({
+		name: z.string().min(1),
+		tokenUrl: z.string().url().optional(),
+		apiBaseUrl: z.string().url().nullable().optional(),
+		flow: z.enum(connectorFlowValues).optional(),
+		clientIdValueName: z.string().min(1).optional(),
+		clientSecretSecretName: z.string().min(1).nullable().optional(),
+		accessTokenSecretName: z.string().min(1).optional(),
+		refreshTokenSecretName: z.string().min(1).nullable().optional(),
+		requiredHosts: z.array(z.string()).optional(),
+	})
+	.strict()
+
+export type ConnectorUpdate = z.infer<typeof connectorUpdateSchema>
+
 export function normalizeConnectorConfig(
 	value: ConnectorConfig,
 ): ConnectorConfig {
@@ -23,6 +40,7 @@
 		...value,
 		name: value.name.trim(),
 		tokenUrl: value.tokenUrl.trim(),
+		apiBaseUrl: value.apiBaseUrl?.trim() || null,
 		clientIdValueName: value.clientIdValueName.trim(),
 		clientSecretSecretName: value.clientSecretSecretName?.trim() || null,
 		accessTokenSecretName: value.accessTokenSecretName.trim(),
@@ -31,6 +49,17 @@
 	}
 }
 
+export function mergeConnectorConfig(
+	current: ConnectorConfig,
+	update: ConnectorUpdate,
+): ConnectorConfig {
+	return normalizeConnectorConfig({
+		...current,
+		...update,
+		name: update.name.trim(),
+	})
+}
+
 const connectorValuePrefix = '_connector:'
 
 export function buildConnectorValueName(name: string) {

diff --git a/packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts b/packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts
new file mode 100644
--- /dev/null
+++ b/packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts
@@ -1,0 +1,182 @@
+import { expect, test } from 'vitest'
+import { createMcpCallerContext } from '#mcp/context.ts'
+import { connectorUpdateCapability } from './connector-update.ts'
+import {
+	connectorConfigSchema,
+	mergeConnectorConfig,
+	parseConnectorConfig,
+} from './connector-shared.ts'
+
+function createValueTestDb() {
+	const entries = new Map<string, string>()
+
+	const db = {
+		prepare(query: string) {
+			const normalizedQuery = query.replace(/\s+/g, ' ').trim().toLowerCase()
+			return {
+				bind(...params: Array<unknown>) {
+					return {
+						async first<T>() {
+							if (
+								normalizedQuery.startsWith('select') &&
+								normalizedQuery.includes('from value_buckets')
+							) {
+								return {
+									id: 'bucket-1',
+									user_id: String(params[0]),
+									scope: String(params[1]),
+									binding_key: '',
+									expires_at: null,
+									created_at: '2026-03-29T00:00:00.000Z',
+									updated_at: '2026-03-29T00:00:00.000Z',
+								} as T
+							}
+							if (
+								normalizedQuery.startsWith('select') &&
+								normalizedQuery.includes('from value_entries') &&
+								normalizedQuery.includes('where bucket_id = ? and name = ?')
+							) {
+								const name = String(params[1])
+								const value = entries.get(name)
+								return value == null
+									? null
+									: ({
+											bucket_id: 'bucket-1',
+											name,
+											description: `OAuth connector config for ${name}`,
+											value,
+											created_at: '2026-03-29T00:00:00.000Z',
+											updated_at: '2026-03-29T00:00:00.000Z',
+										} as T)
+							}
+							return null
+						},
+						async run() {
+							if (normalizedQuery.startsWith('insert into value_entries')) {
+								const name = String(params[1])
+								const value = String(params[3])
+								entries.set(name, value)
+								return { meta: { changes: 1 } }
+							}
+							return { meta: { changes: 1 } }
+						},
+					}
+				},
+			}
+		},
+	} as unknown as D1Database
+
+	return { db, entries }
+}
+
+test('mergeConnectorConfig applies patch fields and preserves existing fields', () => {
+	const current = connectorConfigSchema.parse({
+		name: 'spotify',
+		tokenUrl: 'https://accounts.spotify.com/api/token',
+		apiBaseUrl: 'https://api.spotify.com/v1',
+		flow: 'pkce',
+		clientIdValueName: 'spotify-client-id',
+		clientSecretSecretName: null,
+		accessTokenSecretName: 'spotifyAccessToken',
+		refreshTokenSecretName: 'spotifyRefreshToken',
+		requiredHosts: ['accounts.spotify.com', 'api.spotify.com'],
+	})
+
+	const merged = mergeConnectorConfig(current, {
+		name: 'spotify',
+		apiBaseUrl: 'https://api.spotify.com/v2/',
+		requiredHosts: ['api.spotify.com'],
+	})
+
+	expect(merged).toEqual({
+		...current,
+		apiBaseUrl: 'https://api.spotify.com/v2/',
+		requiredHosts: ['api.spotify.com'],
+	})
+})
+
+test('parseConnectorConfig keeps older rows readable when apiBaseUrl is missing', () => {
+	const parsed = parseConnectorConfig(
+		{
+			name: 'spotify',
+			tokenUrl: 'https://accounts.spotify.com/api/token',
+			flow: 'pkce',
+			clientIdValueName: 'spotify-client-id',
+			clientSecretSecretName: null,
+			accessTokenSecretName: 'spotifyAccessToken',
+			refreshTokenSecretName: 'spotifyRefreshToken',
+			requiredHosts: ['api.spotify.com'],
+		},
+		null,
+	)
+
+	expect(parsed).toMatchObject({
+		name: 'spotify',
+		apiBaseUrl: null,
+	})
+})
+
+test('connector_update updates an existing connector record', async () => {
+	const testDb = createValueTestDb()
+	testDb.entries.set(
+		'_connector:spotify',
+		JSON.stringify({
+			name: 'spotify',
+			tokenUrl: 'https://accounts.spotify.com/api/token',
+			apiBaseUrl: null,
+			flow: 'pkce',
+			clientIdValueName: 'spotify-client-id',
+			clientSecretSecretName: null,
+			accessTokenSecretName: 'spotifyAccessToken',
+			refreshTokenSecretName: 'spotifyRefreshToken',
+			requiredHosts: ['accounts.spotify.com', 'api.spotify.com'],
+		}),
+	)
+
+	const result = await connectorUpdateCapability.handler(
+		{
+			name: 'spotify',
+			apiBaseUrl: 'https://api.spotify.com/v1',
+			requiredHosts: ['api.spotify.com'],
+		},
+		{
+			env: { APP_DB: testDb.db } as unknown as Env,
+			callerContext: createMcpCallerContext({
+				baseUrl: 'https://heykody.dev',
+				user: { userId: 'user-123' },
+			}),
+		},
+	)
+
+	expect(result.connector).toMatchObject({
+		name: 'spotify',
+		apiBaseUrl: 'https://api.spotify.com/v1',
+		requiredHosts: ['api.spotify.com'],
+	})
+	expect(
+		JSON.parse(testDb.entries.get('_connector:spotify') ?? '{}'),
+	).toMatchObject({
+		apiBaseUrl: 'https://api.spotify.com/v1',
+		requiredHosts: ['api.spotify.com'],
+	})
+})
+
+test('connector_update rejects missing connector records', async () => {
+	const testDb = createValueTestDb()
+
+	await expect(
+		connectorUpdateCapability.handler(
+			{
+				name: 'spotify',
+				apiBaseUrl: 'https://api.spotify.com/v1',
+			},
+			{
+				env: { APP_DB: testDb.db } as unknown as Env,
+				callerContext: createMcpCallerContext({
+					baseUrl: 'https://heykody.dev',
+					user: { userId: 'user-123' },
+				}),
+			},
+		),
+	).rejects.toThrow('Connector "spotify" was not found.')
+})

diff --git a/packages/worker/src/mcp/capabilities/values/connector-update.ts b/packages/worker/src/mcp/capabilities/values/connector-update.ts
new file mode 100644
--- /dev/null
+++ b/packages/worker/src/mcp/capabilities/values/connector-update.ts
@@ -1,0 +1,88 @@
+import { z } from 'zod'
+import { defineDomainCapability } from '#mcp/capabilities/define-domain-capability.ts'
+import { capabilityDomainNames } from '#mcp/capabilities/domain-metadata.ts'
+import { requireMcpUser } from '#mcp/capabilities/meta/require-user.ts'
+import { type CapabilityContext } from '#mcp/capabilities/types.ts'
+import { getValue, saveValue } from '#mcp/values/service.ts'
+import {
+	buildConnectorValueName,
+	connectorConfigSchema,
+	connectorUpdateSchema,
+	mergeConnectorConfig,
+	parseConnectorConfig,
+	parseConnectorJson,
+} from './connector-shared.ts'
+
+const inputSchema = connectorUpdateSchema
+
+const outputSchema = z.object({
+	connector: connectorConfigSchema,
+})
+
+export const connectorUpdateCapability = defineDomainCapability(
+	capabilityDomainNames.values,
+	{
+		name: 'connector_update',
+		description:
+			'Update an existing OAuth connector configuration by name. Supports patch-style edits for connector config fields.',
+		keywords: [
+			'connector',
+			'oauth',
+			'config',
+			'registry',
+			'update',
+			'patch',
+			'edit',
+			'value',
+		],
+		readOnly: false,
+		idempotent: true,
+		destructive: false,
+		inputSchema,
+		outputSchema,
+		async handler(args, ctx: CapabilityContext) {
+			const user = requireMcpUser(ctx.callerContext)
+			const normalizedName = args.name.trim()
+			const storageContext = {
+				sessionId: ctx.callerContext.storageContext?.sessionId ?? null,
+				appId: ctx.callerContext.storageContext?.appId ?? null,
+			}
+			const existing = await getValue({
+				env: ctx.env,
+				userId: user.userId,
+				name: buildConnectorValueName(normalizedName),
+				scope: 'user',
+				storageContext,
+			})
+			if (!existing) {
+				throw new Error(`Connector "${normalizedName}" was not found.`)
+			}
+			const current = parseConnectorConfig(
+				parseConnectorJson(existing.value),
+				normalizedName,
+			)
+			if (!current) {
+				throw new Error(
+					`Connector "${normalizedName}" is stored with invalid JSON.`,
+				)
+			}
+			const connector = mergeConnectorConfig(current, args)
+			const value = await saveValue({
+				env: ctx.env,
+				userId: user.userId,
+				name: buildConnectorValueName(connector.name),
+				value: JSON.stringify(connector),
+				scope: 'user',
+				description: `OAuth connector config for ${connector.name}`,
+				storageContext,
+			})
+			const parsed = parseConnectorConfig(
+				parseConnectorJson(value.value),
+				connector.name,
+			)
+			return {
+				connector: parsed ?? connector,
+			}
+		},
+	},
+)

diff --git a/packages/worker/src/mcp/capabilities/values/domain.ts b/packages/worker/src/mcp/capabilities/values/domain.ts
--- a/packages/worker/src/mcp/capabilities/values/domain.ts
+++ b/packages/worker/src/mcp/capabilities/values/domain.ts
@@ -4,6 +4,7 @@
 import { connectorGetCapability } from './connector-get.ts'
 import { connectorListCapability } from './connector-list.ts'
 import { connectorSaveCapability } from './connector-save.ts'
+import { connectorUpdateCapability } from './connector-update.ts'
 import { valueDeleteCapability } from './value-delete.ts'
 import { valueGetCapability } from './value-get.ts'
 import { valueListCapability } from './value-list.ts'
@@ -20,6 +21,7 @@
 		valueListCapability,
 		valueDeleteCapability,
 		connectorSaveCapability,
+		connectorUpdateCapability,
 		connectorGetCapability,
 		connectorListCapability,
 		connectorDeleteCapability,

diff --git a/packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts b/packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
new file mode 100644
--- /dev/null
+++ b/packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
@@ -1,0 +1,212 @@
+import { expect, test } from 'vitest'
+import {
+	createAuthenticatedFetch,
+	createCodemodeUtils,
+	refreshAccessToken,
+} from './codemode-utils.ts'
+
+type CodemodeUtilsNamespace = Parameters<typeof refreshAccessToken>[0]
+
+type MockCodemode = {
+	connector_get: (args: { name: string }) => Promise<{
+		connector: {
+			name: string
+			tokenUrl: string
+			apiBaseUrl: string | null
+			flow: 'pkce' | 'confidential'
+			clientIdValueName: string
+			clientSecretSecretName: string | null
+			accessTokenSecretName: string
+			refreshTokenSecretName: string | null
+			requiredHosts?: Array<string>
+		} | null
+	}>
+	value_get: (args: { name: string }) => Promise<{ value: string } | null>
+}
+
+function createMockCodemode(
+	overrides?: Partial<{
+		connector: Awaited<ReturnType<MockCodemode['connector_get']>>['connector']
+		clientId: string | null
+	}>,
+): MockCodemode {
+	return {
+		async connector_get() {
+			return {
+				connector:
+					'connector' in (overrides ?? {})
+						? (overrides?.connector ?? null)
+						: {
+								name: 'spotify',
+								tokenUrl: 'https://accounts.spotify.com/api/token',
+								apiBaseUrl: 'https://api.spotify.com/v1',
+								flow: 'pkce',
+								clientIdValueName: 'spotify-client-id',
+								clientSecretSecretName: null,
+								accessTokenSecretName: 'spotifyAccessToken',
+								refreshTokenSecretName: 'spotifyRefreshToken',
+								requiredHosts: ['accounts.spotify.com', 'api.spotify.com'],
+							},
+			}
+		},
+		async value_get() {
+			if (overrides?.clientId === null) return null
+			return { value: overrides?.clientId ?? 'spotify-client-id-value' }
+		},
+	}
+}
+
+test('refreshAccessToken posts refresh-token form payload and returns the token', async () => {
+	const codemode = createMockCodemode() as unknown as CodemodeUtilsNamespace
+	const requests: Array<Request> = []
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async (input, init) => {
+		const request = new Request(input, init)
+		requests.push(request)
+		return Response.json({
+			access_token: 'fresh-access-token',
+			token_type: 'Bearer',
+		})
+	}
+
+	try {
+		const token = await refreshAccessToken(codemode, 'spotify')
+		expect(token).toBe('fresh-access-token')
+		expect(requests).toHaveLength(1)
+		const request = requests[0]
+		const body = await request?.text()
+		expect(request?.url).toBe('https://accounts.spotify.com/api/token')
+		expect(request?.method).toBe('POST')
+		expect(request?.headers.get('Content-Type')).toBe(
+			'application/x-www-form-urlencoded',
+		)
+		expect(body).toContain('grant_type=refresh_token')
+		expect(body).toContain(
+			'refresh_token=%7B%7Bsecret%3AspotifyRefreshToken%7Cscope%3Duser%7D%7D',
+		)
+		expect(body).toContain('client_id=spotify-client-id-value')
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})
+
+test('refreshAccessToken includes client secret placeholder for confidential connectors', async () => {
+	const codemode = createMockCodemode({
+		connector: {
+			name: 'linear',
+			tokenUrl: 'https://api.linear.app/oauth/token',
+			apiBaseUrl: 'https://api.linear.app',
+			flow: 'confidential',
+			clientIdValueName: 'linear-client-id',
+			clientSecretSecretName: 'linearClientSecret',
+			accessTokenSecretName: 'linearAccessToken',
+			refreshTokenSecretName: 'linearRefreshToken',
+			requiredHosts: ['api.linear.app'],
+		},
+	}) as unknown as CodemodeUtilsNamespace
+	const requests: Array<Request> = []
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async (input, init) => {
+		requests.push(new Request(input, init))
+		return Response.json({ access_token: 'linear-token' })
+	}
+
+	try {
+		await refreshAccessToken(codemode, 'linear')
+		const body = await requests[0]?.text()
+		expect(body).toContain(
+			'client_secret=%7B%7Bsecret%3AlinearClientSecret%7Cscope%3Duser%7D%7D',
+		)
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})
+
+test('createAuthenticatedFetch resolves relative URLs against apiBaseUrl and injects bearer token', async () => {
+	const codemode = createMockCodemode() as unknown as CodemodeUtilsNamespace
+	const requests: Array<Request> = []
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async (input, init) => {
+		const request = new Request(input, init)
+		requests.push(request)
+		if (requests.length === 1) {
+			return Response.json({ access_token: 'fresh-access-token' })
+		}
+		return Response.json({ ok: true })
+	}
+
+	try {
+		const authFetch = await createAuthenticatedFetch(codemode, 'spotify')
+		const response = await authFetch('/me/player')
+		expect(response.ok).toBe(true)
+		expect(requests).toHaveLength(2)
+		const apiRequest = requests[1]
+		expect(apiRequest?.url).toBe('https://api.spotify.com/v1/me/player')
+		expect(apiRequest?.headers.get('Authorization')).toBe(
+			'Bearer fresh-access-token',
+		)
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})
+
+test('createCodemodeUtils binds helper methods to codemode', async () => {
+	const codemode = createMockCodemode() as unknown as CodemodeUtilsNamespace
+	const requests: Array<Request> = []
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async (input, init) => {
+		requests.push(new Request(input, init))
+		return Response.json({ access_token: 'bound-token' })
+	}
+
+	try {
+		const utils = createCodemodeUtils(codemode)
+		const token = await utils.refreshAccessToken('spotify')
+		expect(token).toBe('bound-token')
+		expect(requests).toHaveLength(1)
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})
+
+test('refreshAccessToken fails clearly when the connector is missing', async () => {
+	const codemode = createMockCodemode({
+		connector: null,
+	}) as unknown as CodemodeUtilsNamespace
+	await expect(refreshAccessToken(codemode, 'spotify')).rejects.toThrow(
+		'Connector "spotify" was not found.',
+	)
+})
+
+test('createAuthenticatedFetch rejects relative URLs without apiBaseUrl', async () => {
+	const codemode = createMockCodemode({
+		connector: {
+			name: 'spotify',
+			tokenUrl: 'https://accounts.spotify.com/api/token',
+			apiBaseUrl: null,
+			flow: 'pkce',
+			clientIdValueName: 'spotify-client-id',
+			clientSecretSecretName: null,
+			accessTokenSecretName: 'spotifyAccessToken',
+			refreshTokenSecretName: 'spotifyRefreshToken',
+			requiredHosts: ['accounts.spotify.com'],
+		},
+	}) as unknown as CodemodeUtilsNamespace
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async () =>
+		Response.json({ access_token: 'fresh-access-token' })
+
+	try {
+		const authFetch = await createAuthenticatedFetch(codemode, 'spotify')
+		await expect(authFetch('/me/player')).rejects.toThrow(
+			'Connector "spotify" does not define apiBaseUrl for relative requests.',
+		)
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})

diff --git a/packages/worker/src/mcp/execute-modules/codemode-utils.ts b/packages/worker/src/mcp/execute-modules/codemode-utils.ts
new file mode 100644
--- /dev/null
+++ b/packages/worker/src/mcp/execute-modules/codemode-utils.ts
@@ -1,0 +1,247 @@
+type CapabilityResult = unknown
+
+type CapabilityArgs = Record<string, unknown>
+
+type CodemodeNamespace = Record<
+	string,
+	(args: CapabilityArgs) => Promise<CapabilityResult>
+>
+
+type ConnectorConfig = {
+	name: string
+	tokenUrl: string
+	apiBaseUrl?: string | null
+	flow: 'pkce' | 'confidential'
+	clientIdValueName: string
+	clientSecretSecretName?: string | null
+	accessTokenSecretName: string
+	refreshTokenSecretName?: string | null
+	requiredHosts?: Array<string>
+}
+
+type ConnectorGetResult = {
+	connector: ConnectorConfig | null
+}
+
+type ValueGetResult = {
+	name: string
+	scope: string
+	value: string
+	description: string
+	app_id: string | null
+	created_at: string
+	updated_at: string
+	ttl_ms: number | null
+} | null
+
... diff truncated: showing 800 of 1402 lines
Open in Web Open in Cursor 


You can also dynamically import \`@kody/codemode-utils\` from inside your async
function for connector OAuth helpers such as
\`refreshAccessToken(providerName)\` and \`createAuthenticatedFetch(providerName)\`.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cursoragent I think we need much more than this. I would like full type definitions in here. Or maybe a capability that retrieves docs and include a reference to that capability here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taking a look!

Open in Web Open in Cursor 

cursoragent and others added 2 commits March 29, 2026 18:09
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
@@ -0,0 +1,7 @@
// Generated by tools/build-codemode-sandbox-modules.ts. Do not edit by hand.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cursoragent should this be gitignored? I don't normally like committing generated files to source.

@cursor cursor Bot Mar 29, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Relative URL resolution silently skipped for Request inputs
    • Requests constructed with a runtime-origin URL now get their path resolved against apiBaseUrl while already-resolved connector URLs stay untouched.
  • ✅ Fixed: Connector update lookup uses raw but saves normalized name
    • The update handler now trims the connector name before lookup and error reporting to ensure the read and write keys match.

Create PR

Preview (b48606ec5f)
diff --git a/nx.json b/nx.json
--- a/nx.json
+++ b/nx.json
@@ -8,6 +8,9 @@
 		"build": {
 			"cache": true
 		},
+		"build-codemode-sandbox-modules": {
+			"cache": true
+		},
 		"build-client": {
 			"cache": true
 		},
@@ -17,6 +20,12 @@
 		"build-mcp-apps": {
 			"cache": true
 		},
+		"test": {
+			"cache": true
+		},
+		"test-mcp": {
+			"cache": true
+		},
 		"dev": {
 			"cache": false
 		},

diff --git a/package.json b/package.json
--- a/package.json
+++ b/package.json
@@ -22,6 +22,7 @@
   },
   "scripts": {
     "dev": "node --env-file=packages/worker/.env cli.ts",
+    "build:codemode-sandbox-modules": "node tools/build-codemode-sandbox-modules.ts",
     "dev:home-connector": "npm --prefix packages/home-connector run dev",
     "dev:client": "concurrently --kill-others-on-fail -n web,mcp-apps -c green,cyan \"npm run dev:client:web\" \"npm run dev:mcp-apps\"",
     "dev:client:web": "esbuild packages/worker/client/entry.tsx --bundle --format=esm --target=es2022 --outdir=packages/worker/public --entry-names=client-entry --chunk-names=assets/[name] --asset-names=assets/[name] --jsx=automatic --jsx-import-source=remix/component --watch",
@@ -37,7 +38,7 @@
     "build:mcp-apps": "esbuild packages/worker/client/mcp-apps/kody-ui-utils.ts --bundle --format=esm --target=es2022 --outfile=packages/worker/public/mcp-apps/kody-ui-utils.js --platform=browser --banner:js='/* eslint-disable no-undef */'",
     "build:client:web": "esbuild packages/worker/client/entry.tsx --bundle --format=esm --target=es2022 --outdir=packages/worker/public --entry-names=client-entry --chunk-names=assets/[name] --asset-names=assets/[name] --jsx=automatic --jsx-import-source=remix/component",
     "build:client": "npm run build:client:web && npm run build:mcp-apps",
-    "build": "npm run build:client && node --env-file=packages/worker/.env ./wrangler-env.ts build",
+    "build": "npx nx run worker:build",
     "lint": "oxlint .",
     "lint:fix": "oxlint . --fix",
     "format": "oxfmt",
@@ -48,13 +49,13 @@
     "preview:e2e": "node --env-file=packages/worker/.env tools/prepare-e2e-env.ts && npx nx run worker:build-client && npm run migrate:e2e && node --env-file=packages/worker/.env ./wrangler-env.ts dev --local --persist-to .wrangler/state/e2e",
     "generate-types": "node --env-file=packages/worker/.env ./wrangler-env.ts types ./packages/worker/worker-configuration.d.ts",
     "typecheck": "tsc -b --noEmit",
-    "test": "vitest run --project node-unit --project workers-unit",
+    "test": "npx nx run worker:test",
     "inspect": "npx -y @mcpjam/inspector inspector",
     "validate": "concurrently --kill-others-on-fail -n format,lint,build,typecheck,test,test:mcp -c green,yellow,blue,magenta,cyan,red \"npm run format:check\" \"npm run lint:fix\" \"npm run build\" \"npm run typecheck\" \"npm run test:e2e\" \"npm run test:mcp\"",
     "test:e2e": "playwright test",
     "test:e2e:ui": "playwright test --ui",
     "test:e2e:install": "playwright install chromium --with-deps",
-    "test:mcp": "node tools/prepare-e2e-env.ts && npm run build:mcp-apps && vitest run --project mcp-e2e",
+    "test:mcp": "npx nx run worker:test-mcp",
     "prepare": "husky",
     "nx:graph": "nx graph",
     "nx:show-projects": "nx show projects"

diff --git a/packages/worker/client/routes/connect-oauth.tsx b/packages/worker/client/routes/connect-oauth.tsx
--- a/packages/worker/client/routes/connect-oauth.tsx
+++ b/packages/worker/client/routes/connect-oauth.tsx
@@ -10,6 +10,7 @@
 	tokenHost: string
 	authorizeUrl: string
 	tokenUrl: string
+	apiBaseUrl: string | null
 	scopes: Array<string>
 	flow: OAuthFlow
 	scopeSeparator: string
@@ -93,6 +94,7 @@
 		const provider = readRequired('provider')
 		const authorizeUrl = readRequired('authorizeUrl')
 		const tokenUrl = readRequired('tokenUrl')
+		const apiBaseUrl = parseOptionalUrl(readOptional('apiBaseUrl'))
 		if (!provider || !authorizeUrl || !tokenUrl) {
 			hasConfigError = true
 			setStatus('Missing required OAuth configuration parameters.', 'error')
@@ -138,6 +140,7 @@
 			tokenHost,
 			authorizeUrl,
 			tokenUrl,
+			apiBaseUrl,
 			scopes,
 			flow: flow as OAuthFlow,
 			scopeSeparator,
@@ -521,6 +524,7 @@
 				provider: config.provider,
 				callbackUrl,
 				tokenUrl: config.tokenUrl,
+				apiBaseUrl: config.apiBaseUrl,
 				flow: config.flow,
 				clientIdValueName: config.clientIdValueName,
 				clientSecretSecretName: config.clientSecretSecretName,

diff --git a/packages/worker/project.json b/packages/worker/project.json
--- a/packages/worker/project.json
+++ b/packages/worker/project.json
@@ -10,6 +10,21 @@
 				"command": "npm run dev"
 			}
 		},
+		"build-codemode-sandbox-modules": {
+			"executor": "nx:run-commands",
+			"inputs": [
+				"default",
+				"{workspaceRoot}/tools/build-codemode-sandbox-modules.ts",
+				"{workspaceRoot}/package.json",
+				"{workspaceRoot}/package-lock.json"
+			],
+			"outputs": [
+				"{workspaceRoot}/packages/worker/src/mcp/generated/codemode-sandbox-modules.ts"
+			],
+			"options": {
+				"command": "npm run build:codemode-sandbox-modules"
+			}
+		},
 		"dev-client": {
 			"executor": "nx:run-commands",
 			"options": {
@@ -41,6 +56,7 @@
 		},
 		"build-client": {
 			"executor": "nx:run-commands",
+			"dependsOn": ["build-codemode-sandbox-modules"],
 			"outputs": [
 				"{workspaceRoot}/packages/worker/public/client-entry.js",
 				"{workspaceRoot}/packages/worker/public/assets",
@@ -52,10 +68,25 @@
 		},
 		"build": {
 			"executor": "nx:run-commands",
+			"dependsOn": ["build-client"],
 			"options": {
-				"command": "npm run build"
+				"command": "node --env-file=packages/worker/.env ./wrangler-env.ts build"
 			}
 		},
+		"test": {
+			"executor": "nx:run-commands",
+			"dependsOn": ["build-codemode-sandbox-modules"],
+			"options": {
+				"command": "vitest run --project node-unit --project workers-unit"
+			}
+		},
+		"test-mcp": {
+			"executor": "nx:run-commands",
+			"dependsOn": ["build-codemode-sandbox-modules", "build-mcp-apps"],
+			"options": {
+				"command": "node tools/prepare-e2e-env.ts && vitest run --project mcp-e2e"
+			}
+		},
 		"deploy": {
 			"executor": "nx:run-commands",
 			"options": {

diff --git a/packages/worker/src/app/handlers/account-secrets.ts b/packages/worker/src/app/handlers/account-secrets.ts
--- a/packages/worker/src/app/handlers/account-secrets.ts
+++ b/packages/worker/src/app/handlers/account-secrets.ts
@@ -237,6 +237,7 @@
 }) {
 	const provider = readString(input.body, 'provider')
 	const tokenUrl = readOptionalString(input.body, 'tokenUrl')
+	const apiBaseUrl = readOptionalString(input.body, 'apiBaseUrl')
 	const flow = readOptionalString(input.body, 'flow')
 	const clientIdValueName = readOptionalString(input.body, 'clientIdValueName')
 	const clientSecretSecretName = readOptionalString(
@@ -345,6 +346,7 @@
 		userId: input.user.mcpUser.userId,
 		provider,
 		tokenUrl,
+		apiBaseUrl,
 		flow: flow === 'confidential' ? 'confidential' : 'pkce',
 		clientIdValueName,
 		clientSecretSecretName,
@@ -449,6 +451,7 @@
 	userId: string
 	provider: string
 	tokenUrl: string
+	apiBaseUrl: string | null
 	flow: 'pkce' | 'confidential'
 	clientIdValueName: string
 	clientSecretSecretName: string | null
@@ -464,6 +467,7 @@
 	const connector = normalizeConnectorConfig({
 		name: input.provider,
 		tokenUrl: input.tokenUrl,
+		apiBaseUrl: input.apiBaseUrl,
 		flow: input.flow,
 		clientIdValueName: input.clientIdValueName,
 		clientSecretSecretName:

diff --git a/packages/worker/src/mcp/capabilities/values/connector-save.ts b/packages/worker/src/mcp/capabilities/values/connector-save.ts
--- a/packages/worker/src/mcp/capabilities/values/connector-save.ts
+++ b/packages/worker/src/mcp/capabilities/values/connector-save.ts
@@ -23,7 +23,7 @@
 	{
 		name: 'connector_save',
 		description:
-			'Save an OAuth connector configuration for the signed-in user. Stored as a user-scoped value with a _connector: prefix.',
+			'Save or replace an OAuth connector configuration for the signed-in user. Stored as a user-scoped value with a _connector: prefix.',
 		keywords: ['connector', 'oauth', 'config', 'registry', 'save', 'value'],
 		readOnly: false,
 		idempotent: false,

diff --git a/packages/worker/src/mcp/capabilities/values/connector-shared.ts b/packages/worker/src/mcp/capabilities/values/connector-shared.ts
--- a/packages/worker/src/mcp/capabilities/values/connector-shared.ts
+++ b/packages/worker/src/mcp/capabilities/values/connector-shared.ts
@@ -6,6 +6,7 @@
 export const connectorConfigSchema = z.object({
 	name: z.string().min(1),
 	tokenUrl: z.string().url(),
+	apiBaseUrl: z.string().url().optional().nullable(),
 	flow: z.enum(connectorFlowValues),
 	clientIdValueName: z.string().min(1),
 	clientSecretSecretName: z.string().min(1).optional().nullable(),
@@ -16,6 +17,22 @@
 
 export type ConnectorConfig = z.infer<typeof connectorConfigSchema>
 
+export const connectorUpdateSchema = z
+	.object({
+		name: z.string().min(1),
+		tokenUrl: z.string().url().optional(),
+		apiBaseUrl: z.string().url().nullable().optional(),
+		flow: z.enum(connectorFlowValues).optional(),
+		clientIdValueName: z.string().min(1).optional(),
+		clientSecretSecretName: z.string().min(1).nullable().optional(),
+		accessTokenSecretName: z.string().min(1).optional(),
+		refreshTokenSecretName: z.string().min(1).nullable().optional(),
+		requiredHosts: z.array(z.string()).optional(),
+	})
+	.strict()
+
+export type ConnectorUpdate = z.infer<typeof connectorUpdateSchema>
+
 export function normalizeConnectorConfig(
 	value: ConnectorConfig,
 ): ConnectorConfig {
@@ -23,6 +40,7 @@
 		...value,
 		name: value.name.trim(),
 		tokenUrl: value.tokenUrl.trim(),
+		apiBaseUrl: value.apiBaseUrl?.trim() || null,
 		clientIdValueName: value.clientIdValueName.trim(),
 		clientSecretSecretName: value.clientSecretSecretName?.trim() || null,
 		accessTokenSecretName: value.accessTokenSecretName.trim(),
@@ -31,6 +49,17 @@
 	}
 }
 
+export function mergeConnectorConfig(
+	current: ConnectorConfig,
+	update: ConnectorUpdate,
+): ConnectorConfig {
+	return normalizeConnectorConfig({
+		...current,
+		...update,
+		name: update.name.trim(),
+	})
+}
+
 const connectorValuePrefix = '_connector:'
 
 export function buildConnectorValueName(name: string) {

diff --git a/packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts b/packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts
new file mode 100644
--- /dev/null
+++ b/packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts
@@ -1,0 +1,182 @@
+import { expect, test } from 'vitest'
+import { createMcpCallerContext } from '#mcp/context.ts'
+import { connectorUpdateCapability } from './connector-update.ts'
+import {
+	connectorConfigSchema,
+	mergeConnectorConfig,
+	parseConnectorConfig,
+} from './connector-shared.ts'
+
+function createValueTestDb() {
+	const entries = new Map<string, string>()
+
+	const db = {
+		prepare(query: string) {
+			const normalizedQuery = query.replace(/\s+/g, ' ').trim().toLowerCase()
+			return {
+				bind(...params: Array<unknown>) {
+					return {
+						async first<T>() {
+							if (
+								normalizedQuery.startsWith('select') &&
+								normalizedQuery.includes('from value_buckets')
+							) {
+								return {
+									id: 'bucket-1',
+									user_id: String(params[0]),
+									scope: String(params[1]),
+									binding_key: '',
+									expires_at: null,
+									created_at: '2026-03-29T00:00:00.000Z',
+									updated_at: '2026-03-29T00:00:00.000Z',
+								} as T
+							}
+							if (
+								normalizedQuery.startsWith('select') &&
+								normalizedQuery.includes('from value_entries') &&
+								normalizedQuery.includes('where bucket_id = ? and name = ?')
+							) {
+								const name = String(params[1])
+								const value = entries.get(name)
+								return value == null
+									? null
+									: ({
+											bucket_id: 'bucket-1',
+											name,
+											description: `OAuth connector config for ${name}`,
+											value,
+											created_at: '2026-03-29T00:00:00.000Z',
+											updated_at: '2026-03-29T00:00:00.000Z',
+										} as T)
+							}
+							return null
+						},
+						async run() {
+							if (normalizedQuery.startsWith('insert into value_entries')) {
+								const name = String(params[1])
+								const value = String(params[3])
+								entries.set(name, value)
+								return { meta: { changes: 1 } }
+							}
+							return { meta: { changes: 1 } }
+						},
+					}
+				},
+			}
+		},
+	} as unknown as D1Database
+
+	return { db, entries }
+}
+
+test('mergeConnectorConfig applies patch fields and preserves existing fields', () => {
+	const current = connectorConfigSchema.parse({
+		name: 'spotify',
+		tokenUrl: 'https://accounts.spotify.com/api/token',
+		apiBaseUrl: 'https://api.spotify.com/v1',
+		flow: 'pkce',
+		clientIdValueName: 'spotify-client-id',
+		clientSecretSecretName: null,
+		accessTokenSecretName: 'spotifyAccessToken',
+		refreshTokenSecretName: 'spotifyRefreshToken',
+		requiredHosts: ['accounts.spotify.com', 'api.spotify.com'],
+	})
+
+	const merged = mergeConnectorConfig(current, {
+		name: 'spotify',
+		apiBaseUrl: 'https://api.spotify.com/v2/',
+		requiredHosts: ['api.spotify.com'],
+	})
+
+	expect(merged).toEqual({
+		...current,
+		apiBaseUrl: 'https://api.spotify.com/v2/',
+		requiredHosts: ['api.spotify.com'],
+	})
+})
+
+test('parseConnectorConfig keeps older rows readable when apiBaseUrl is missing', () => {
+	const parsed = parseConnectorConfig(
+		{
+			name: 'spotify',
+			tokenUrl: 'https://accounts.spotify.com/api/token',
+			flow: 'pkce',
+			clientIdValueName: 'spotify-client-id',
+			clientSecretSecretName: null,
+			accessTokenSecretName: 'spotifyAccessToken',
+			refreshTokenSecretName: 'spotifyRefreshToken',
+			requiredHosts: ['api.spotify.com'],
+		},
+		null,
+	)
+
+	expect(parsed).toMatchObject({
+		name: 'spotify',
+		apiBaseUrl: null,
+	})
+})
+
+test('connector_update updates an existing connector record', async () => {
+	const testDb = createValueTestDb()
+	testDb.entries.set(
+		'_connector:spotify',
+		JSON.stringify({
+			name: 'spotify',
+			tokenUrl: 'https://accounts.spotify.com/api/token',
+			apiBaseUrl: null,
+			flow: 'pkce',
+			clientIdValueName: 'spotify-client-id',
+			clientSecretSecretName: null,
+			accessTokenSecretName: 'spotifyAccessToken',
+			refreshTokenSecretName: 'spotifyRefreshToken',
+			requiredHosts: ['accounts.spotify.com', 'api.spotify.com'],
+		}),
+	)
+
+	const result = await connectorUpdateCapability.handler(
+		{
+			name: 'spotify',
+			apiBaseUrl: 'https://api.spotify.com/v1',
+			requiredHosts: ['api.spotify.com'],
+		},
+		{
+			env: { APP_DB: testDb.db } as unknown as Env,
+			callerContext: createMcpCallerContext({
+				baseUrl: 'https://heykody.dev',
+				user: { userId: 'user-123' },
+			}),
+		},
+	)
+
+	expect(result.connector).toMatchObject({
+		name: 'spotify',
+		apiBaseUrl: 'https://api.spotify.com/v1',
+		requiredHosts: ['api.spotify.com'],
+	})
+	expect(
+		JSON.parse(testDb.entries.get('_connector:spotify') ?? '{}'),
+	).toMatchObject({
+		apiBaseUrl: 'https://api.spotify.com/v1',
+		requiredHosts: ['api.spotify.com'],
+	})
+})
+
+test('connector_update rejects missing connector records', async () => {
+	const testDb = createValueTestDb()
+
+	await expect(
+		connectorUpdateCapability.handler(
+			{
+				name: 'spotify',
+				apiBaseUrl: 'https://api.spotify.com/v1',
+			},
+			{
+				env: { APP_DB: testDb.db } as unknown as Env,
+				callerContext: createMcpCallerContext({
+					baseUrl: 'https://heykody.dev',
+					user: { userId: 'user-123' },
+				}),
+			},
+		),
+	).rejects.toThrow('Connector "spotify" was not found.')
+})

diff --git a/packages/worker/src/mcp/capabilities/values/connector-update.ts b/packages/worker/src/mcp/capabilities/values/connector-update.ts
new file mode 100644
--- /dev/null
+++ b/packages/worker/src/mcp/capabilities/values/connector-update.ts
@@ -1,0 +1,88 @@
+import { z } from 'zod'
+import { defineDomainCapability } from '#mcp/capabilities/define-domain-capability.ts'
+import { capabilityDomainNames } from '#mcp/capabilities/domain-metadata.ts'
+import { requireMcpUser } from '#mcp/capabilities/meta/require-user.ts'
+import { type CapabilityContext } from '#mcp/capabilities/types.ts'
+import { getValue, saveValue } from '#mcp/values/service.ts'
+import {
+	buildConnectorValueName,
+	connectorConfigSchema,
+	connectorUpdateSchema,
+	mergeConnectorConfig,
+	parseConnectorConfig,
+	parseConnectorJson,
+} from './connector-shared.ts'
+
+const inputSchema = connectorUpdateSchema
+
+const outputSchema = z.object({
+	connector: connectorConfigSchema,
+})
+
+export const connectorUpdateCapability = defineDomainCapability(
+	capabilityDomainNames.values,
+	{
+		name: 'connector_update',
+		description:
+			'Update an existing OAuth connector configuration by name. Supports patch-style edits for connector config fields.',
+		keywords: [
+			'connector',
+			'oauth',
+			'config',
+			'registry',
+			'update',
+			'patch',
+			'edit',
+			'value',
+		],
+		readOnly: false,
+		idempotent: true,
+		destructive: false,
+		inputSchema,
+		outputSchema,
+		async handler(args, ctx: CapabilityContext) {
+			const user = requireMcpUser(ctx.callerContext)
+			const normalizedName = args.name.trim()
+			const storageContext = {
+				sessionId: ctx.callerContext.storageContext?.sessionId ?? null,
+				appId: ctx.callerContext.storageContext?.appId ?? null,
+			}
+			const existing = await getValue({
+				env: ctx.env,
+				userId: user.userId,
+				name: buildConnectorValueName(normalizedName),
+				scope: 'user',
+				storageContext,
+			})
+			if (!existing) {
+				throw new Error(`Connector "${normalizedName}" was not found.`)
+			}
+			const current = parseConnectorConfig(
+				parseConnectorJson(existing.value),
+				normalizedName,
+			)
+			if (!current) {
+				throw new Error(
+					`Connector "${normalizedName}" is stored with invalid JSON.`,
+				)
+			}
+			const connector = mergeConnectorConfig(current, args)
+			const value = await saveValue({
+				env: ctx.env,
+				userId: user.userId,
+				name: buildConnectorValueName(connector.name),
+				value: JSON.stringify(connector),
+				scope: 'user',
+				description: `OAuth connector config for ${connector.name}`,
+				storageContext,
+			})
+			const parsed = parseConnectorConfig(
+				parseConnectorJson(value.value),
+				connector.name,
+			)
+			return {
+				connector: parsed ?? connector,
+			}
+		},
+	},
+)

diff --git a/packages/worker/src/mcp/capabilities/values/domain.ts b/packages/worker/src/mcp/capabilities/values/domain.ts
--- a/packages/worker/src/mcp/capabilities/values/domain.ts
+++ b/packages/worker/src/mcp/capabilities/values/domain.ts
@@ -4,6 +4,7 @@
 import { connectorGetCapability } from './connector-get.ts'
 import { connectorListCapability } from './connector-list.ts'
 import { connectorSaveCapability } from './connector-save.ts'
+import { connectorUpdateCapability } from './connector-update.ts'
 import { valueDeleteCapability } from './value-delete.ts'
 import { valueGetCapability } from './value-get.ts'
 import { valueListCapability } from './value-list.ts'
@@ -20,6 +21,7 @@
 		valueListCapability,
 		valueDeleteCapability,
 		connectorSaveCapability,
+		connectorUpdateCapability,
 		connectorGetCapability,
 		connectorListCapability,
 		connectorDeleteCapability,

diff --git a/packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts b/packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
new file mode 100644
--- /dev/null
+++ b/packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
@@ -1,0 +1,212 @@
+import { expect, test } from 'vitest'
+import {
+	createAuthenticatedFetch,
+	createCodemodeUtils,
+	refreshAccessToken,
+} from './codemode-utils.ts'
+
+type CodemodeUtilsNamespace = Parameters<typeof refreshAccessToken>[0]
+
+type MockCodemode = {
+	connector_get: (args: { name: string }) => Promise<{
+		connector: {
+			name: string
+			tokenUrl: string
+			apiBaseUrl: string | null
+			flow: 'pkce' | 'confidential'
+			clientIdValueName: string
+			clientSecretSecretName: string | null
+			accessTokenSecretName: string
+			refreshTokenSecretName: string | null
+			requiredHosts?: Array<string>
+		} | null
+	}>
+	value_get: (args: { name: string }) => Promise<{ value: string } | null>
+}
+
+function createMockCodemode(
+	overrides?: Partial<{
+		connector: Awaited<ReturnType<MockCodemode['connector_get']>>['connector']
+		clientId: string | null
+	}>,
+): MockCodemode {
+	return {
+		async connector_get() {
+			return {
+				connector:
+					'connector' in (overrides ?? {})
+						? (overrides?.connector ?? null)
+						: {
+								name: 'spotify',
+								tokenUrl: 'https://accounts.spotify.com/api/token',
+								apiBaseUrl: 'https://api.spotify.com/v1',
+								flow: 'pkce',
+								clientIdValueName: 'spotify-client-id',
+								clientSecretSecretName: null,
+								accessTokenSecretName: 'spotifyAccessToken',
+								refreshTokenSecretName: 'spotifyRefreshToken',
+								requiredHosts: ['accounts.spotify.com', 'api.spotify.com'],
+							},
+			}
+		},
+		async value_get() {
+			if (overrides?.clientId === null) return null
+			return { value: overrides?.clientId ?? 'spotify-client-id-value' }
+		},
+	}
+}
+
+test('refreshAccessToken posts refresh-token form payload and returns the token', async () => {
+	const codemode = createMockCodemode() as unknown as CodemodeUtilsNamespace
+	const requests: Array<Request> = []
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async (input, init) => {
+		const request = new Request(input, init)
+		requests.push(request)
+		return Response.json({
+			access_token: 'fresh-access-token',
+			token_type: 'Bearer',
+		})
+	}
+
+	try {
+		const token = await refreshAccessToken(codemode, 'spotify')
+		expect(token).toBe('fresh-access-token')
+		expect(requests).toHaveLength(1)
+		const request = requests[0]
+		const body = await request?.text()
+		expect(request?.url).toBe('https://accounts.spotify.com/api/token')
+		expect(request?.method).toBe('POST')
+		expect(request?.headers.get('Content-Type')).toBe(
+			'application/x-www-form-urlencoded',
+		)
+		expect(body).toContain('grant_type=refresh_token')
+		expect(body).toContain(
+			'refresh_token=%7B%7Bsecret%3AspotifyRefreshToken%7Cscope%3Duser%7D%7D',
+		)
+		expect(body).toContain('client_id=spotify-client-id-value')
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})
+
+test('refreshAccessToken includes client secret placeholder for confidential connectors', async () => {
+	const codemode = createMockCodemode({
+		connector: {
+			name: 'linear',
+			tokenUrl: 'https://api.linear.app/oauth/token',
+			apiBaseUrl: 'https://api.linear.app',
+			flow: 'confidential',
+			clientIdValueName: 'linear-client-id',
+			clientSecretSecretName: 'linearClientSecret',
+			accessTokenSecretName: 'linearAccessToken',
+			refreshTokenSecretName: 'linearRefreshToken',
+			requiredHosts: ['api.linear.app'],
+		},
+	}) as unknown as CodemodeUtilsNamespace
+	const requests: Array<Request> = []
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async (input, init) => {
+		requests.push(new Request(input, init))
+		return Response.json({ access_token: 'linear-token' })
+	}
+
+	try {
+		await refreshAccessToken(codemode, 'linear')
+		const body = await requests[0]?.text()
+		expect(body).toContain(
+			'client_secret=%7B%7Bsecret%3AlinearClientSecret%7Cscope%3Duser%7D%7D',
+		)
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})
+
+test('createAuthenticatedFetch resolves relative URLs against apiBaseUrl and injects bearer token', async () => {
+	const codemode = createMockCodemode() as unknown as CodemodeUtilsNamespace
+	const requests: Array<Request> = []
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async (input, init) => {
+		const request = new Request(input, init)
+		requests.push(request)
+		if (requests.length === 1) {
+			return Response.json({ access_token: 'fresh-access-token' })
+		}
+		return Response.json({ ok: true })
+	}
+
+	try {
+		const authFetch = await createAuthenticatedFetch(codemode, 'spotify')
+		const response = await authFetch('/me/player')
+		expect(response.ok).toBe(true)
+		expect(requests).toHaveLength(2)
+		const apiRequest = requests[1]
+		expect(apiRequest?.url).toBe('https://api.spotify.com/v1/me/player')
+		expect(apiRequest?.headers.get('Authorization')).toBe(
+			'Bearer fresh-access-token',
+		)
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})
+
+test('createCodemodeUtils binds helper methods to codemode', async () => {
+	const codemode = createMockCodemode() as unknown as CodemodeUtilsNamespace
+	const requests: Array<Request> = []
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async (input, init) => {
+		requests.push(new Request(input, init))
+		return Response.json({ access_token: 'bound-token' })
+	}
+
+	try {
+		const utils = createCodemodeUtils(codemode)
+		const token = await utils.refreshAccessToken('spotify')
+		expect(token).toBe('bound-token')
+		expect(requests).toHaveLength(1)
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})
+
+test('refreshAccessToken fails clearly when the connector is missing', async () => {
+	const codemode = createMockCodemode({
+		connector: null,
+	}) as unknown as CodemodeUtilsNamespace
+	await expect(refreshAccessToken(codemode, 'spotify')).rejects.toThrow(
+		'Connector "spotify" was not found.',
+	)
+})
+
+test('createAuthenticatedFetch rejects relative URLs without apiBaseUrl', async () => {
+	const codemode = createMockCodemode({
+		connector: {
+			name: 'spotify',
+			tokenUrl: 'https://accounts.spotify.com/api/token',
+			apiBaseUrl: null,
+			flow: 'pkce',
+			clientIdValueName: 'spotify-client-id',
+			clientSecretSecretName: null,
+			accessTokenSecretName: 'spotifyAccessToken',
+			refreshTokenSecretName: 'spotifyRefreshToken',
+			requiredHosts: ['accounts.spotify.com'],
+		},
+	}) as unknown as CodemodeUtilsNamespace
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async () =>
+		Response.json({ access_token: 'fresh-access-token' })
+
+	try {
+		const authFetch = await createAuthenticatedFetch(codemode, 'spotify')
+		await expect(authFetch('/me/player')).rejects.toThrow(
+			'Connector "spotify" does not define apiBaseUrl for relative requests.',
+		)
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})

diff --git a/packages/worker/src/mcp/execute-modules/codemode-utils.ts b/packages/worker/src/mcp/execute-modules/codemode-utils.ts
new file mode 100644
--- /dev/null
+++ b/packages/worker/src/mcp/execute-modules/codemode-utils.ts
@@ -1,0 +1,247 @@
+type CapabilityResult = unknown
+
+type CapabilityArgs = Record<string, unknown>
+
... diff truncated: showing 800 of 1434 lines
Open in Web Open in Cursor 

Comment on lines +55 to +56
const { createCodemodeUtils } = await import('@kody/codemode-utils');
const { createAuthenticatedFetch } = createCodemodeUtils(codemode);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cursoragent, is it not possible for @kody/codemode-utils to have access to codemode itself somehow? I don't like the requirement of createCodemodeUtils unless it's absolutely a limitation we can't avoid.

@cursor cursor Bot Mar 29, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Relative URL resolution silently skipped for Request inputs
    • Requests constructed with a runtime-origin URL now get their path resolved against apiBaseUrl while already-resolved connector URLs stay untouched.
  • ✅ Fixed: Connector update lookup uses raw but saves normalized name
    • The update handler now trims the connector name before lookup and error reporting to ensure the read and write keys match.

Create PR

Preview (8bbb64a5af)
diff --git a/nx.json b/nx.json
--- a/nx.json
+++ b/nx.json
@@ -8,6 +8,9 @@
 		"build": {
 			"cache": true
 		},
+		"build-codemode-sandbox-modules": {
+			"cache": true
+		},
 		"build-client": {
 			"cache": true
 		},
@@ -17,6 +20,12 @@
 		"build-mcp-apps": {
 			"cache": true
 		},
+		"test": {
+			"cache": true
+		},
+		"test-mcp": {
+			"cache": true
+		},
 		"dev": {
 			"cache": false
 		},

diff --git a/package.json b/package.json
--- a/package.json
+++ b/package.json
@@ -22,6 +22,7 @@
   },
   "scripts": {
     "dev": "node --env-file=packages/worker/.env cli.ts",
+    "build:codemode-sandbox-modules": "node tools/build-codemode-sandbox-modules.ts",
     "dev:home-connector": "npm --prefix packages/home-connector run dev",
     "dev:client": "concurrently --kill-others-on-fail -n web,mcp-apps -c green,cyan \"npm run dev:client:web\" \"npm run dev:mcp-apps\"",
     "dev:client:web": "esbuild packages/worker/client/entry.tsx --bundle --format=esm --target=es2022 --outdir=packages/worker/public --entry-names=client-entry --chunk-names=assets/[name] --asset-names=assets/[name] --jsx=automatic --jsx-import-source=remix/component --watch",
@@ -37,7 +38,7 @@
     "build:mcp-apps": "esbuild packages/worker/client/mcp-apps/kody-ui-utils.ts --bundle --format=esm --target=es2022 --outfile=packages/worker/public/mcp-apps/kody-ui-utils.js --platform=browser --banner:js='/* eslint-disable no-undef */'",
     "build:client:web": "esbuild packages/worker/client/entry.tsx --bundle --format=esm --target=es2022 --outdir=packages/worker/public --entry-names=client-entry --chunk-names=assets/[name] --asset-names=assets/[name] --jsx=automatic --jsx-import-source=remix/component",
     "build:client": "npm run build:client:web && npm run build:mcp-apps",
-    "build": "npm run build:client && node --env-file=packages/worker/.env ./wrangler-env.ts build",
+    "build": "npx nx run worker:build",
     "lint": "oxlint .",
     "lint:fix": "oxlint . --fix",
     "format": "oxfmt",
@@ -48,13 +49,13 @@
     "preview:e2e": "node --env-file=packages/worker/.env tools/prepare-e2e-env.ts && npx nx run worker:build-client && npm run migrate:e2e && node --env-file=packages/worker/.env ./wrangler-env.ts dev --local --persist-to .wrangler/state/e2e",
     "generate-types": "node --env-file=packages/worker/.env ./wrangler-env.ts types ./packages/worker/worker-configuration.d.ts",
     "typecheck": "tsc -b --noEmit",
-    "test": "vitest run --project node-unit --project workers-unit",
+    "test": "npx nx run worker:test",
     "inspect": "npx -y @mcpjam/inspector inspector",
     "validate": "concurrently --kill-others-on-fail -n format,lint,build,typecheck,test,test:mcp -c green,yellow,blue,magenta,cyan,red \"npm run format:check\" \"npm run lint:fix\" \"npm run build\" \"npm run typecheck\" \"npm run test:e2e\" \"npm run test:mcp\"",
     "test:e2e": "playwright test",
     "test:e2e:ui": "playwright test --ui",
     "test:e2e:install": "playwright install chromium --with-deps",
-    "test:mcp": "node tools/prepare-e2e-env.ts && npm run build:mcp-apps && vitest run --project mcp-e2e",
+    "test:mcp": "npx nx run worker:test-mcp",
     "prepare": "husky",
     "nx:graph": "nx graph",
     "nx:show-projects": "nx show projects"

diff --git a/packages/worker/client/routes/connect-oauth.tsx b/packages/worker/client/routes/connect-oauth.tsx
--- a/packages/worker/client/routes/connect-oauth.tsx
+++ b/packages/worker/client/routes/connect-oauth.tsx
@@ -10,6 +10,7 @@
 	tokenHost: string
 	authorizeUrl: string
 	tokenUrl: string
+	apiBaseUrl: string | null
 	scopes: Array<string>
 	flow: OAuthFlow
 	scopeSeparator: string
@@ -93,6 +94,7 @@
 		const provider = readRequired('provider')
 		const authorizeUrl = readRequired('authorizeUrl')
 		const tokenUrl = readRequired('tokenUrl')
+		const apiBaseUrl = parseOptionalUrl(readOptional('apiBaseUrl'))
 		if (!provider || !authorizeUrl || !tokenUrl) {
 			hasConfigError = true
 			setStatus('Missing required OAuth configuration parameters.', 'error')
@@ -138,6 +140,7 @@
 			tokenHost,
 			authorizeUrl,
 			tokenUrl,
+			apiBaseUrl,
 			scopes,
 			flow: flow as OAuthFlow,
 			scopeSeparator,
@@ -521,6 +524,7 @@
 				provider: config.provider,
 				callbackUrl,
 				tokenUrl: config.tokenUrl,
+				apiBaseUrl: config.apiBaseUrl,
 				flow: config.flow,
 				clientIdValueName: config.clientIdValueName,
 				clientSecretSecretName: config.clientSecretSecretName,

diff --git a/packages/worker/project.json b/packages/worker/project.json
--- a/packages/worker/project.json
+++ b/packages/worker/project.json
@@ -10,6 +10,21 @@
 				"command": "npm run dev"
 			}
 		},
+		"build-codemode-sandbox-modules": {
+			"executor": "nx:run-commands",
+			"inputs": [
+				"default",
+				"{workspaceRoot}/tools/build-codemode-sandbox-modules.ts",
+				"{workspaceRoot}/package.json",
+				"{workspaceRoot}/package-lock.json"
+			],
+			"outputs": [
+				"{workspaceRoot}/packages/worker/src/mcp/generated/codemode-sandbox-modules.ts"
+			],
+			"options": {
+				"command": "npm run build:codemode-sandbox-modules"
+			}
+		},
 		"dev-client": {
 			"executor": "nx:run-commands",
 			"options": {
@@ -41,6 +56,7 @@
 		},
 		"build-client": {
 			"executor": "nx:run-commands",
+			"dependsOn": ["build-codemode-sandbox-modules"],
 			"outputs": [
 				"{workspaceRoot}/packages/worker/public/client-entry.js",
 				"{workspaceRoot}/packages/worker/public/assets",
@@ -52,10 +68,25 @@
 		},
 		"build": {
 			"executor": "nx:run-commands",
+			"dependsOn": ["build-client"],
 			"options": {
-				"command": "npm run build"
+				"command": "node --env-file=packages/worker/.env ./wrangler-env.ts build"
 			}
 		},
+		"test": {
+			"executor": "nx:run-commands",
+			"dependsOn": ["build-codemode-sandbox-modules"],
+			"options": {
+				"command": "vitest run --project node-unit --project workers-unit"
+			}
+		},
+		"test-mcp": {
+			"executor": "nx:run-commands",
+			"dependsOn": ["build-codemode-sandbox-modules", "build-mcp-apps"],
+			"options": {
+				"command": "node tools/prepare-e2e-env.ts && vitest run --project mcp-e2e"
+			}
+		},
 		"deploy": {
 			"executor": "nx:run-commands",
 			"options": {

diff --git a/packages/worker/src/app/handlers/account-secrets.ts b/packages/worker/src/app/handlers/account-secrets.ts
--- a/packages/worker/src/app/handlers/account-secrets.ts
+++ b/packages/worker/src/app/handlers/account-secrets.ts
@@ -237,6 +237,7 @@
 }) {
 	const provider = readString(input.body, 'provider')
 	const tokenUrl = readOptionalString(input.body, 'tokenUrl')
+	const apiBaseUrl = readOptionalString(input.body, 'apiBaseUrl')
 	const flow = readOptionalString(input.body, 'flow')
 	const clientIdValueName = readOptionalString(input.body, 'clientIdValueName')
 	const clientSecretSecretName = readOptionalString(
@@ -345,6 +346,7 @@
 		userId: input.user.mcpUser.userId,
 		provider,
 		tokenUrl,
+		apiBaseUrl,
 		flow: flow === 'confidential' ? 'confidential' : 'pkce',
 		clientIdValueName,
 		clientSecretSecretName,
@@ -449,6 +451,7 @@
 	userId: string
 	provider: string
 	tokenUrl: string
+	apiBaseUrl: string | null
 	flow: 'pkce' | 'confidential'
 	clientIdValueName: string
 	clientSecretSecretName: string | null
@@ -464,6 +467,7 @@
 	const connector = normalizeConnectorConfig({
 		name: input.provider,
 		tokenUrl: input.tokenUrl,
+		apiBaseUrl: input.apiBaseUrl,
 		flow: input.flow,
 		clientIdValueName: input.clientIdValueName,
 		clientSecretSecretName:

diff --git a/packages/worker/src/mcp/capabilities/values/connector-save.ts b/packages/worker/src/mcp/capabilities/values/connector-save.ts
--- a/packages/worker/src/mcp/capabilities/values/connector-save.ts
+++ b/packages/worker/src/mcp/capabilities/values/connector-save.ts
@@ -23,7 +23,7 @@
 	{
 		name: 'connector_save',
 		description:
-			'Save an OAuth connector configuration for the signed-in user. Stored as a user-scoped value with a _connector: prefix.',
+			'Save or replace an OAuth connector configuration for the signed-in user. Stored as a user-scoped value with a _connector: prefix.',
 		keywords: ['connector', 'oauth', 'config', 'registry', 'save', 'value'],
 		readOnly: false,
 		idempotent: false,

diff --git a/packages/worker/src/mcp/capabilities/values/connector-shared.ts b/packages/worker/src/mcp/capabilities/values/connector-shared.ts
--- a/packages/worker/src/mcp/capabilities/values/connector-shared.ts
+++ b/packages/worker/src/mcp/capabilities/values/connector-shared.ts
@@ -6,6 +6,7 @@
 export const connectorConfigSchema = z.object({
 	name: z.string().min(1),
 	tokenUrl: z.string().url(),
+	apiBaseUrl: z.string().url().optional().nullable(),
 	flow: z.enum(connectorFlowValues),
 	clientIdValueName: z.string().min(1),
 	clientSecretSecretName: z.string().min(1).optional().nullable(),
@@ -16,6 +17,22 @@
 
 export type ConnectorConfig = z.infer<typeof connectorConfigSchema>
 
+export const connectorUpdateSchema = z
+	.object({
+		name: z.string().min(1),
+		tokenUrl: z.string().url().optional(),
+		apiBaseUrl: z.string().url().nullable().optional(),
+		flow: z.enum(connectorFlowValues).optional(),
+		clientIdValueName: z.string().min(1).optional(),
+		clientSecretSecretName: z.string().min(1).nullable().optional(),
+		accessTokenSecretName: z.string().min(1).optional(),
+		refreshTokenSecretName: z.string().min(1).nullable().optional(),
+		requiredHosts: z.array(z.string()).optional(),
+	})
+	.strict()
+
+export type ConnectorUpdate = z.infer<typeof connectorUpdateSchema>
+
 export function normalizeConnectorConfig(
 	value: ConnectorConfig,
 ): ConnectorConfig {
@@ -23,6 +40,7 @@
 		...value,
 		name: value.name.trim(),
 		tokenUrl: value.tokenUrl.trim(),
+		apiBaseUrl: value.apiBaseUrl?.trim() || null,
 		clientIdValueName: value.clientIdValueName.trim(),
 		clientSecretSecretName: value.clientSecretSecretName?.trim() || null,
 		accessTokenSecretName: value.accessTokenSecretName.trim(),
@@ -31,6 +49,17 @@
 	}
 }
 
+export function mergeConnectorConfig(
+	current: ConnectorConfig,
+	update: ConnectorUpdate,
+): ConnectorConfig {
+	return normalizeConnectorConfig({
+		...current,
+		...update,
+		name: update.name.trim(),
+	})
+}
+
 const connectorValuePrefix = '_connector:'
 
 export function buildConnectorValueName(name: string) {

diff --git a/packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts b/packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts
new file mode 100644
--- /dev/null
+++ b/packages/worker/src/mcp/capabilities/values/connector-update.node.test.ts
@@ -1,0 +1,182 @@
+import { expect, test } from 'vitest'
+import { createMcpCallerContext } from '#mcp/context.ts'
+import { connectorUpdateCapability } from './connector-update.ts'
+import {
+	connectorConfigSchema,
+	mergeConnectorConfig,
+	parseConnectorConfig,
+} from './connector-shared.ts'
+
+function createValueTestDb() {
+	const entries = new Map<string, string>()
+
+	const db = {
+		prepare(query: string) {
+			const normalizedQuery = query.replace(/\s+/g, ' ').trim().toLowerCase()
+			return {
+				bind(...params: Array<unknown>) {
+					return {
+						async first<T>() {
+							if (
+								normalizedQuery.startsWith('select') &&
+								normalizedQuery.includes('from value_buckets')
+							) {
+								return {
+									id: 'bucket-1',
+									user_id: String(params[0]),
+									scope: String(params[1]),
+									binding_key: '',
+									expires_at: null,
+									created_at: '2026-03-29T00:00:00.000Z',
+									updated_at: '2026-03-29T00:00:00.000Z',
+								} as T
+							}
+							if (
+								normalizedQuery.startsWith('select') &&
+								normalizedQuery.includes('from value_entries') &&
+								normalizedQuery.includes('where bucket_id = ? and name = ?')
+							) {
+								const name = String(params[1])
+								const value = entries.get(name)
+								return value == null
+									? null
+									: ({
+											bucket_id: 'bucket-1',
+											name,
+											description: `OAuth connector config for ${name}`,
+											value,
+											created_at: '2026-03-29T00:00:00.000Z',
+											updated_at: '2026-03-29T00:00:00.000Z',
+										} as T)
+							}
+							return null
+						},
+						async run() {
+							if (normalizedQuery.startsWith('insert into value_entries')) {
+								const name = String(params[1])
+								const value = String(params[3])
+								entries.set(name, value)
+								return { meta: { changes: 1 } }
+							}
+							return { meta: { changes: 1 } }
+						},
+					}
+				},
+			}
+		},
+	} as unknown as D1Database
+
+	return { db, entries }
+}
+
+test('mergeConnectorConfig applies patch fields and preserves existing fields', () => {
+	const current = connectorConfigSchema.parse({
+		name: 'spotify',
+		tokenUrl: 'https://accounts.spotify.com/api/token',
+		apiBaseUrl: 'https://api.spotify.com/v1',
+		flow: 'pkce',
+		clientIdValueName: 'spotify-client-id',
+		clientSecretSecretName: null,
+		accessTokenSecretName: 'spotifyAccessToken',
+		refreshTokenSecretName: 'spotifyRefreshToken',
+		requiredHosts: ['accounts.spotify.com', 'api.spotify.com'],
+	})
+
+	const merged = mergeConnectorConfig(current, {
+		name: 'spotify',
+		apiBaseUrl: 'https://api.spotify.com/v2/',
+		requiredHosts: ['api.spotify.com'],
+	})
+
+	expect(merged).toEqual({
+		...current,
+		apiBaseUrl: 'https://api.spotify.com/v2/',
+		requiredHosts: ['api.spotify.com'],
+	})
+})
+
+test('parseConnectorConfig keeps older rows readable when apiBaseUrl is missing', () => {
+	const parsed = parseConnectorConfig(
+		{
+			name: 'spotify',
+			tokenUrl: 'https://accounts.spotify.com/api/token',
+			flow: 'pkce',
+			clientIdValueName: 'spotify-client-id',
+			clientSecretSecretName: null,
+			accessTokenSecretName: 'spotifyAccessToken',
+			refreshTokenSecretName: 'spotifyRefreshToken',
+			requiredHosts: ['api.spotify.com'],
+		},
+		null,
+	)
+
+	expect(parsed).toMatchObject({
+		name: 'spotify',
+		apiBaseUrl: null,
+	})
+})
+
+test('connector_update updates an existing connector record', async () => {
+	const testDb = createValueTestDb()
+	testDb.entries.set(
+		'_connector:spotify',
+		JSON.stringify({
+			name: 'spotify',
+			tokenUrl: 'https://accounts.spotify.com/api/token',
+			apiBaseUrl: null,
+			flow: 'pkce',
+			clientIdValueName: 'spotify-client-id',
+			clientSecretSecretName: null,
+			accessTokenSecretName: 'spotifyAccessToken',
+			refreshTokenSecretName: 'spotifyRefreshToken',
+			requiredHosts: ['accounts.spotify.com', 'api.spotify.com'],
+		}),
+	)
+
+	const result = await connectorUpdateCapability.handler(
+		{
+			name: 'spotify',
+			apiBaseUrl: 'https://api.spotify.com/v1',
+			requiredHosts: ['api.spotify.com'],
+		},
+		{
+			env: { APP_DB: testDb.db } as unknown as Env,
+			callerContext: createMcpCallerContext({
+				baseUrl: 'https://heykody.dev',
+				user: { userId: 'user-123' },
+			}),
+		},
+	)
+
+	expect(result.connector).toMatchObject({
+		name: 'spotify',
+		apiBaseUrl: 'https://api.spotify.com/v1',
+		requiredHosts: ['api.spotify.com'],
+	})
+	expect(
+		JSON.parse(testDb.entries.get('_connector:spotify') ?? '{}'),
+	).toMatchObject({
+		apiBaseUrl: 'https://api.spotify.com/v1',
+		requiredHosts: ['api.spotify.com'],
+	})
+})
+
+test('connector_update rejects missing connector records', async () => {
+	const testDb = createValueTestDb()
+
+	await expect(
+		connectorUpdateCapability.handler(
+			{
+				name: 'spotify',
+				apiBaseUrl: 'https://api.spotify.com/v1',
+			},
+			{
+				env: { APP_DB: testDb.db } as unknown as Env,
+				callerContext: createMcpCallerContext({
+					baseUrl: 'https://heykody.dev',
+					user: { userId: 'user-123' },
+				}),
+			},
+		),
+	).rejects.toThrow('Connector "spotify" was not found.')
+})

diff --git a/packages/worker/src/mcp/capabilities/values/connector-update.ts b/packages/worker/src/mcp/capabilities/values/connector-update.ts
new file mode 100644
--- /dev/null
+++ b/packages/worker/src/mcp/capabilities/values/connector-update.ts
@@ -1,0 +1,88 @@
+import { z } from 'zod'
+import { defineDomainCapability } from '#mcp/capabilities/define-domain-capability.ts'
+import { capabilityDomainNames } from '#mcp/capabilities/domain-metadata.ts'
+import { requireMcpUser } from '#mcp/capabilities/meta/require-user.ts'
+import { type CapabilityContext } from '#mcp/capabilities/types.ts'
+import { getValue, saveValue } from '#mcp/values/service.ts'
+import {
+	buildConnectorValueName,
+	connectorConfigSchema,
+	connectorUpdateSchema,
+	mergeConnectorConfig,
+	parseConnectorConfig,
+	parseConnectorJson,
+} from './connector-shared.ts'
+
+const inputSchema = connectorUpdateSchema
+
+const outputSchema = z.object({
+	connector: connectorConfigSchema,
+})
+
+export const connectorUpdateCapability = defineDomainCapability(
+	capabilityDomainNames.values,
+	{
+		name: 'connector_update',
+		description:
+			'Update an existing OAuth connector configuration by name. Supports patch-style edits for connector config fields.',
+		keywords: [
+			'connector',
+			'oauth',
+			'config',
+			'registry',
+			'update',
+			'patch',
+			'edit',
+			'value',
+		],
+		readOnly: false,
+		idempotent: true,
+		destructive: false,
+		inputSchema,
+		outputSchema,
+		async handler(args, ctx: CapabilityContext) {
+			const user = requireMcpUser(ctx.callerContext)
+			const normalizedName = args.name.trim()
+			const storageContext = {
+				sessionId: ctx.callerContext.storageContext?.sessionId ?? null,
+				appId: ctx.callerContext.storageContext?.appId ?? null,
+			}
+			const existing = await getValue({
+				env: ctx.env,
+				userId: user.userId,
+				name: buildConnectorValueName(normalizedName),
+				scope: 'user',
+				storageContext,
+			})
+			if (!existing) {
+				throw new Error(`Connector "${normalizedName}" was not found.`)
+			}
+			const current = parseConnectorConfig(
+				parseConnectorJson(existing.value),
+				normalizedName,
+			)
+			if (!current) {
+				throw new Error(
+					`Connector "${normalizedName}" is stored with invalid JSON.`,
+				)
+			}
+			const connector = mergeConnectorConfig(current, args)
+			const value = await saveValue({
+				env: ctx.env,
+				userId: user.userId,
+				name: buildConnectorValueName(connector.name),
+				value: JSON.stringify(connector),
+				scope: 'user',
+				description: `OAuth connector config for ${connector.name}`,
+				storageContext,
+			})
+			const parsed = parseConnectorConfig(
+				parseConnectorJson(value.value),
+				connector.name,
+			)
+			return {
+				connector: parsed ?? connector,
+			}
+		},
+	},
+)

diff --git a/packages/worker/src/mcp/capabilities/values/domain.ts b/packages/worker/src/mcp/capabilities/values/domain.ts
--- a/packages/worker/src/mcp/capabilities/values/domain.ts
+++ b/packages/worker/src/mcp/capabilities/values/domain.ts
@@ -4,6 +4,7 @@
 import { connectorGetCapability } from './connector-get.ts'
 import { connectorListCapability } from './connector-list.ts'
 import { connectorSaveCapability } from './connector-save.ts'
+import { connectorUpdateCapability } from './connector-update.ts'
 import { valueDeleteCapability } from './value-delete.ts'
 import { valueGetCapability } from './value-get.ts'
 import { valueListCapability } from './value-list.ts'
@@ -20,6 +21,7 @@
 		valueListCapability,
 		valueDeleteCapability,
 		connectorSaveCapability,
+		connectorUpdateCapability,
 		connectorGetCapability,
 		connectorListCapability,
 		connectorDeleteCapability,

diff --git a/packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts b/packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
new file mode 100644
--- /dev/null
+++ b/packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
@@ -1,0 +1,232 @@
+import { expect, test } from 'vitest'
+import {
+	createAuthenticatedFetch,
+	createCodemodeUtils,
+	refreshAccessToken,
+} from './codemode-utils.ts'
+
+type CodemodeUtilsNamespace = Parameters<typeof refreshAccessToken>[0]
+
+type MockCodemode = {
+	connector_get: (args: { name: string }) => Promise<{
+		connector: {
+			name: string
+			tokenUrl: string
+			apiBaseUrl: string | null
+			flow: 'pkce' | 'confidential'
+			clientIdValueName: string
+			clientSecretSecretName: string | null
+			accessTokenSecretName: string
+			refreshTokenSecretName: string | null
+			requiredHosts?: Array<string>
+		} | null
+	}>
+	value_get: (args: { name: string }) => Promise<{ value: string } | null>
+}
+
+function createMockCodemode(
+	overrides?: Partial<{
+		connector: Awaited<ReturnType<MockCodemode['connector_get']>>['connector']
+		clientId: string | null
+	}>,
+): MockCodemode {
+	return {
+		async connector_get() {
+			return {
+				connector:
+					'connector' in (overrides ?? {})
+						? (overrides?.connector ?? null)
+						: {
+								name: 'spotify',
+								tokenUrl: 'https://accounts.spotify.com/api/token',
+								apiBaseUrl: 'https://api.spotify.com/v1',
+								flow: 'pkce',
+								clientIdValueName: 'spotify-client-id',
+								clientSecretSecretName: null,
+								accessTokenSecretName: 'spotifyAccessToken',
+								refreshTokenSecretName: 'spotifyRefreshToken',
+								requiredHosts: ['accounts.spotify.com', 'api.spotify.com'],
+							},
+			}
+		},
+		async value_get() {
+			if (overrides?.clientId === null) return null
+			return { value: overrides?.clientId ?? 'spotify-client-id-value' }
+		},
+	}
+}
+
+test('refreshAccessToken posts refresh-token form payload and returns the token', async () => {
+	const codemode = createMockCodemode() as unknown as CodemodeUtilsNamespace
+	const requests: Array<Request> = []
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async (input, init) => {
+		const request = new Request(input, init)
+		requests.push(request)
+		return Response.json({
+			access_token: 'fresh-access-token',
+			token_type: 'Bearer',
+		})
+	}
+
+	try {
+		const token = await refreshAccessToken(codemode, 'spotify')
+		expect(token).toBe('fresh-access-token')
+		expect(requests).toHaveLength(1)
+		const request = requests[0]
+		const body = await request?.text()
+		expect(request?.url).toBe('https://accounts.spotify.com/api/token')
+		expect(request?.method).toBe('POST')
+		expect(request?.headers.get('Content-Type')).toBe(
+			'application/x-www-form-urlencoded',
+		)
+		expect(body).toContain('grant_type=refresh_token')
+		expect(body).toContain(
+			'refresh_token=%7B%7Bsecret%3AspotifyRefreshToken%7Cscope%3Duser%7D%7D',
+		)
+		expect(body).toContain('client_id=spotify-client-id-value')
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})
+
+test('refreshAccessToken includes client secret placeholder for confidential connectors', async () => {
+	const codemode = createMockCodemode({
+		connector: {
+			name: 'linear',
+			tokenUrl: 'https://api.linear.app/oauth/token',
+			apiBaseUrl: 'https://api.linear.app',
+			flow: 'confidential',
+			clientIdValueName: 'linear-client-id',
+			clientSecretSecretName: 'linearClientSecret',
+			accessTokenSecretName: 'linearAccessToken',
+			refreshTokenSecretName: 'linearRefreshToken',
+			requiredHosts: ['api.linear.app'],
+		},
+	}) as unknown as CodemodeUtilsNamespace
+	const requests: Array<Request> = []
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async (input, init) => {
+		requests.push(new Request(input, init))
+		return Response.json({ access_token: 'linear-token' })
+	}
+
+	try {
+		await refreshAccessToken(codemode, 'linear')
+		const body = await requests[0]?.text()
+		expect(body).toContain(
+			'client_secret=%7B%7Bsecret%3AlinearClientSecret%7Cscope%3Duser%7D%7D',
+		)
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})
+
+test('createAuthenticatedFetch resolves relative URLs against apiBaseUrl and injects bearer token', async () => {
+	const codemode = createMockCodemode() as unknown as CodemodeUtilsNamespace
+	const requests: Array<Request> = []
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async (input, init) => {
+		const request = new Request(input, init)
+		requests.push(request)
+		if (requests.length === 1) {
+			return Response.json({ access_token: 'fresh-access-token' })
+		}
+		return Response.json({ ok: true })
+	}
+
+	try {
+		const authFetch = await createAuthenticatedFetch(codemode, 'spotify')
+		const response = await authFetch('/me/player')
+		expect(response.ok).toBe(true)
+		expect(requests).toHaveLength(2)
+		const apiRequest = requests[1]
+		expect(apiRequest?.url).toBe('https://api.spotify.com/v1/me/player')
+		expect(apiRequest?.headers.get('Authorization')).toBe(
+			'Bearer fresh-access-token',
+		)
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})
+
+test('createCodemodeUtils binds helper methods to codemode', async () => {
+	const codemode = createMockCodemode() as unknown as CodemodeUtilsNamespace
+	const requests: Array<Request> = []
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async (input, init) => {
+		requests.push(new Request(input, init))
+		return Response.json({ access_token: 'bound-token' })
+	}
+
+	try {
+		const utils = createCodemodeUtils(codemode)
+		const token = await utils.refreshAccessToken('spotify')
+		expect(token).toBe('bound-token')
+		expect(requests).toHaveLength(1)
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})
+
+test('helpers can use the bound codemode namespace', async () => {
+	const codemode = createMockCodemode() as unknown as CodemodeUtilsNamespace
+	const requests: Array<Request> = []
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async (input, init) => {
+		requests.push(new Request(input, init))
+		return Response.json({ access_token: 'bound-access-token' })
+	}
+
+	try {
+		createCodemodeUtils(codemode)
+		const token = await refreshAccessToken('spotify')
+		expect(token).toBe('bound-access-token')
+		expect(requests).toHaveLength(1)
+	} finally {
+		globalThis.fetch = originalFetch
+	}
+})
+
+test('refreshAccessToken fails clearly when the connector is missing', async () => {
+	const codemode = createMockCodemode({
+		connector: null,
+	}) as unknown as CodemodeUtilsNamespace
+	await expect(refreshAccessToken(codemode, 'spotify')).rejects.toThrow(
+		'Connector "spotify" was not found.',
+	)
+})
+
+test('createAuthenticatedFetch rejects relative URLs without apiBaseUrl', async () => {
+	const codemode = createMockCodemode({
+		connector: {
+			name: 'spotify',
+			tokenUrl: 'https://accounts.spotify.com/api/token',
+			apiBaseUrl: null,
+			flow: 'pkce',
+			clientIdValueName: 'spotify-client-id',
+			clientSecretSecretName: null,
+			accessTokenSecretName: 'spotifyAccessToken',
+			refreshTokenSecretName: 'spotifyRefreshToken',
+			requiredHosts: ['accounts.spotify.com'],
+		},
+	}) as unknown as CodemodeUtilsNamespace
+	const originalFetch = globalThis.fetch
+
+	globalThis.fetch = async () =>
+		Response.json({ access_token: 'fresh-access-token' })
... diff truncated: showing 800 of 1537 lines
Open in Web Open in Cursor 

cursoragent and others added 3 commits March 29, 2026 18:26
Co-authored-by: me <me@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: me <me@kentcdodds.com>
Co-authored-by: me <me@kentcdodds.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
packages/worker/src/mcp/execute-modules/codemode-utils.ts (2)

254-259: Prefer the shared secret placeholder formatter.

This local helper duplicates packages/worker/src/mcp/secrets/placeholders.ts:28-32. Importing the shared implementation, or extracting a sandbox-safe common module, avoids placeholder-format drift.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/src/mcp/execute-modules/codemode-utils.ts` around lines 254 -
259, The local helper function buildSecretPlaceholder duplicates the shared
formatter; replace its implementation by importing and using the canonical
formatter from the shared module (the formatter in
packages/worker/src/mcp/secrets/placeholders.ts, e.g. its exported function) or
move the shared formatter into a sandbox-safe common module and call that
instead so placeholder formatting is single-source-of-truth; update references
to call the imported formatter and remove the local buildSecretPlaceholder to
prevent drift.

100-109: Narrow authenticated requests to connector hosts.

resolveRequestUrl() leaves absolute URLs untouched, so this wrapper will attach the refreshed bearer token to any destination the caller passes. Using connector.apiBaseUrl / connector.requiredHosts as an allowlist would make the default helper path much safer.

🔐 Proposed guard
 	return async (input: ExecuteRequestInput, init?: RequestInit) => {
 		const request = new Request(resolveRequestUrl(input, connector), init)
+		assertAllowedConnectorHost(request.url, connector)
 		const headers = new Headers(request.headers)
 		headers.set('Authorization', `Bearer ${accessToken}`)
 
 		return fetch(
 			new Request(request, {
@@
 	}
 }
+
+function assertAllowedConnectorHost(requestUrl: string, connector: ConnectorConfig) {
+	const allowedHosts = new Set(connector.requiredHosts ?? [])
+	const normalizedBase = getNormalizedApiBaseUrl(connector)
+	if (normalizedBase) {
+		allowedHosts.add(new URL(normalizedBase).host)
+	}
+	if (allowedHosts.size === 0) return
+	const host = new URL(requestUrl).host
+	if (!allowedHosts.has(host)) {
+		throw new Error(
+			`Connector "${connector.name}" cannot be used against host "${host}".`,
+		)
+	}
+}

Also applies to: 261-277

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/src/mcp/execute-modules/codemode-utils.ts` around lines 100 -
109, The wrapper returned by the async function that creates a Request (calling
resolveRequestUrl and building headers) currently unconditionally injects
Authorization, so change it to only set the Authorization header when the
resolved request URL's host matches the connector allowlist: derive the request
host via new URL(request.url).hostname and compare against
connector.apiBaseUrl's host and any entries in connector.requiredHosts (support
both host and host:port forms); if it matches, set headers.set('Authorization',
`Bearer ${accessToken}`), otherwise do not add the header and proceed with the
fetch; apply the same guarded check to the other similar helper at the other
location noted (lines ~261-277) so tokens are only sent to connector-approved
hosts.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/worker/public/mcp-apps/kody-ui-utils.css`:
- Line 122: The selector uses chained :not() pseudo-classes
(:where(input:not([type=checkbox]):not([type=radio]), textarea, select)) which
triggers the stylelint selector-not-notation rule; replace the chained :not()
calls with a single :not() using a comma-separated list (e.g., change the input
part to input:not([type=checkbox],[type=radio])) so the :where(...) selector
becomes valid under the rule.
- Around line 10-13: The font-family list in kody-ui-utils.css contains unquoted
mixed-case names (SFMono-Regular, Menlo, Monaco, Consolas) which triggers the
value-keyword-case rule; update the font-family declaration that includes these
identifiers to wrap each mixed-case font name in quotes (e.g., "SFMono-Regular",
"Menlo", "Monaco", "Consolas") so the CSS linter treats them as string
identifiers and the rule no longer fails.

In `@packages/worker/src/mcp/execute-modules/codemode-utils.ts`:
- Around line 39-46: Remove the module-global state by deleting the
boundCodemode variable and the setCodemodeUtilsNamespace function, and update
readBoundCodemode to stop using any fallback to that global; instead have
createCodemodeUtils return closures that capture the codemode argument directly
(so refreshAccessToken and createAuthenticatedFetch use the captured codemode
passed into createCodemodeUtils). Ensure no functions rely on the removed
globals (boundCodemode, setCodemodeUtilsNamespace) and that all references are
replaced to use the codemode parameter captured in createCodemodeUtils and its
returned helpers.

---

Nitpick comments:
In `@packages/worker/src/mcp/execute-modules/codemode-utils.ts`:
- Around line 254-259: The local helper function buildSecretPlaceholder
duplicates the shared formatter; replace its implementation by importing and
using the canonical formatter from the shared module (the formatter in
packages/worker/src/mcp/secrets/placeholders.ts, e.g. its exported function) or
move the shared formatter into a sandbox-safe common module and call that
instead so placeholder formatting is single-source-of-truth; update references
to call the imported formatter and remove the local buildSecretPlaceholder to
prevent drift.
- Around line 100-109: The wrapper returned by the async function that creates a
Request (calling resolveRequestUrl and building headers) currently
unconditionally injects Authorization, so change it to only set the
Authorization header when the resolved request URL's host matches the connector
allowlist: derive the request host via new URL(request.url).hostname and compare
against connector.apiBaseUrl's host and any entries in connector.requiredHosts
(support both host and host:port forms); if it matches, set
headers.set('Authorization', `Bearer ${accessToken}`), otherwise do not add the
header and proceed with the fetch; apply the same guarded check to the other
similar helper at the other location noted (lines ~261-277) so tokens are only
sent to connector-approved hosts.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b9afc6e6-48c7-491a-81c7-a52262dd0b2f

📥 Commits

Reviewing files that changed from the base of the PR and between b14dc87 and ba4eb7c.

📒 Files selected for processing (8)
  • .gitignore
  • nx.json
  • package.json
  • packages/worker/project.json
  • packages/worker/public/mcp-apps/kody-ui-utils.css
  • packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
  • packages/worker/src/mcp/execute-modules/codemode-utils.ts
  • packages/worker/src/mcp/tools/execute.ts
✅ Files skipped from review due to trivial changes (3)
  • .gitignore
  • packages/worker/src/mcp/execute-modules/codemode-utils.node.test.ts
  • packages/worker/src/mcp/tools/execute.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • nx.json
  • package.json
  • packages/worker/project.json

Comment on lines +10 to +13
SFMono-Regular,
Menlo,
Monaco,
Consolas,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify mixed-case font tokens are quoted
rg -n 'SFMono-Regular|Menlo|Monaco|Consolas' packages/worker/public/mcp-apps/kody-ui-utils.css

Repository: kentcdodds/kody

Length of output: 127


🏁 Script executed:

#!/bin/bash
# Check for stylelint or CSS linting configuration
find . -type f \( -name ".stylelintrc*" -o -name "stylelint.config.*" -o -name ".eslintrc*" -o -name "package.json" \) | head -20

Repository: kentcdodds/kody

Length of output: 414


🏁 Script executed:

#!/bin/bash
# Read the full CSS file to understand context
cat -n packages/worker/public/mcp-apps/kody-ui-utils.css | head -30

Repository: kentcdodds/kody

Length of output: 967


🏁 Script executed:

#!/bin/bash
# Search for font-family definitions in the file to see if other fonts have similar issues
rg -n "font-family" packages/worker/public/mcp-apps/kody-ui-utils.css -A 5

Repository: kentcdodds/kody

Length of output: 210


🏁 Script executed:

#!/bin/bash
# Check the stylelint configuration
cat -n .stylelintrc.json

Repository: kentcdodds/kody

Length of output: 1275


🏁 Script executed:

#!/bin/bash
# Look for the value-keyword-case rule specifically
rg "value-keyword-case" . --type json

Repository: kentcdodds/kody

Length of output: 41


🏁 Script executed:

#!/bin/bash
# Search for any stylelint comments or directives in the CSS file
cat packages/worker/public/mcp-apps/kody-ui-utils.css | rg -i "stylelint|lint|disable|error"

Repository: kentcdodds/kody

Length of output: 136


🏁 Script executed:

#!/bin/bash
# Check if there are any recent commits mentioning this file or font-family fixes
git log --oneline --all -- packages/worker/public/mcp-apps/kody-ui-utils.css | head -10

Repository: kentcdodds/kody

Length of output: 159


🏁 Script executed:

#!/bin/bash
# Search the repo for any similar quoted font-family patterns to understand the convention
rg "font.*:.*\"" --type css -A 2 | head -40

Repository: kentcdodds/kody

Length of output: 41


🏁 Script executed:

#!/bin/bash
# Check the stylelint-config-standard-scss defaults to understand if value-keyword-case is enabled
npm view stylelint-config-standard-scss 2>/dev/null | head -50

Repository: kentcdodds/kody

Length of output: 942


🏁 Script executed:

#!/bin/bash
# Search for any build/lint commands or CI workflows that might run stylelint
find . -type f \( -name "*.yml" -o -name "*.yaml" -o -name "Makefile" \) | xargs grep -l "stylelint" 2>/dev/null | head -5

Repository: kentcdodds/kody

Length of output: 41


🏁 Script executed:

#!/bin/bash
# Check if there are any comments or documentation about CSS linting rules
rg "value-keyword-case|font.*case" . --type md

Repository: kentcdodds/kody

Length of output: 41


🌐 Web query:

stylelint value-keyword-case rule font-family mixed case

💡 Result:

The stylelint rule "value-keyword-case" enforces lowercase ("lower") or uppercase ("upper") casing for keyword values in CSS declarations. For font-family properties with mixed case (e.g., "OpenSans", "Source Serif", "BlinkMacSystemFont"), it reports violations by default, treating words like "Serif" as keywords that should be "serif". This is a known false positive because font family names are custom identifiers, not keywords. Official docs do not list font-family or font as ignored properties by default. To handle mixed case in font-family: - Use secondary option "ignoreProperties": ["font-family"] or ["font", "font-family"]. Example config: { "rules": { "value-keyword-case": ["lower", { "ignoreProperties": ["font-family"] }] } } - Alternatively, "ignoreKeywords": ["/[A-Z]/"] to ignore any uppercase words, or specific font names/regex. Issues confirming this behavior (#1132, #4622, #5154, #5384) recommend ignoreProperties or quoting fonts (via font-family-name-quotes rule). No automatic ignore for font-family as of latest docs (2026). Quote multi-word fonts per spec recommendation to avoid parsing issues.

Citations:


🏁 Script executed:

#!/bin/bash
# Check if stylelint is actually configured to run and if there are any lint errors being reported
find . -type f \( -name "package.json" -o -name ".github" -o -name ".gitignore" \) -path "*/packages/worker/*" | head -5
cat packages/worker/package.json | head -50

Repository: kentcdodds/kody

Length of output: 405


🏁 Script executed:

#!/bin/bash
# Search more broadly for any quoted font names in CSS files to see the convention used
rg "font-family.*['\"]" --type css -B 2 -A 2 | head -50

Repository: kentcdodds/kody

Length of output: 41


Quote mixed-case font family names to clear value-keyword-case errors.

Unquoted mixed-case names at lines 10-13 are flagged by the active value-keyword-case rule; quoting them prevents the violation and ensures font names are treated as identifiers per CSS specification.

Proposed fix
-    SFMono-Regular,
-    Menlo,
-    Monaco,
-    Consolas,
+    "SFMono-Regular",
+    "Menlo",
+    "Monaco",
+    "Consolas",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
SFMono-Regular,
Menlo,
Monaco,
Consolas,
"SFMono-Regular",
"Menlo",
"Monaco",
"Consolas",
🧰 Tools
🪛 Stylelint (17.5.0)

[error] 10-10: Expected "SFMono-Regular" to be "sfmono-regular" (value-keyword-case)

(value-keyword-case)


[error] 11-11: Expected "Menlo" to be "menlo" (value-keyword-case)

(value-keyword-case)


[error] 12-12: Expected "Monaco" to be "monaco" (value-keyword-case)

(value-keyword-case)


[error] 13-13: Expected "Consolas" to be "consolas" (value-keyword-case)

(value-keyword-case)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/public/mcp-apps/kody-ui-utils.css` around lines 10 - 13, The
font-family list in kody-ui-utils.css contains unquoted mixed-case names
(SFMono-Regular, Menlo, Monaco, Consolas) which triggers the value-keyword-case
rule; update the font-family declaration that includes these identifiers to wrap
each mixed-case font name in quotes (e.g., "SFMono-Regular", "Menlo", "Monaco",
"Consolas") so the CSS linter treats them as string identifiers and the rule no
longer fails.

border: 1px solid var(--color-border);
border-radius: var(--radius-2);
box-shadow: inset 0 1px 2px rgb(15 23 42 / 0.04);
:where(input:not([type=checkbox]):not([type=radio]), textarea, select) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify no chained :not() remains for this selector pattern
rg -nP ':not\(\[type=checkbox\]\):not\(\[type=radio\]\)' packages/worker/public/mcp-apps/kody-ui-utils.css

Repository: kentcdodds/kody

Length of output: 135


Consolidate chained :not() pseudo-classes to fix stylelint error.

Line 122 uses chained :not() notation which violates the selector-not-notation rule. Use the complex :not() list form instead.

Proposed fix
-:where(input:not([type=checkbox]):not([type=radio]), textarea, select) {
+:where(input:not([type=checkbox], [type=radio]), textarea, select) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
:where(input:not([type=checkbox]):not([type=radio]), textarea, select) {
:where(input:not([type=checkbox], [type=radio]), textarea, select) {
🧰 Tools
🪛 Stylelint (17.5.0)

[error] 122-122: Expected complex :not() pseudo-class notation (selector-not-notation)

(selector-not-notation)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/public/mcp-apps/kody-ui-utils.css` at line 122, The selector
uses chained :not() pseudo-classes
(:where(input:not([type=checkbox]):not([type=radio]), textarea, select)) which
triggers the stylelint selector-not-notation rule; replace the chained :not()
calls with a single :not() using a comma-separated list (e.g., change the input
part to input:not([type=checkbox],[type=radio])) so the :where(...) selector
becomes valid under the rule.

cursoragent and others added 2 commits March 29, 2026 19:29
Co-authored-by: me <me@kentcdodds.com>
Co-authored-by: me <me@kentcdodds.com>
cursoragent and others added 4 commits March 29, 2026 19:58
Co-authored-by: me <me@kentcdodds.com>
Co-authored-by: me <me@kentcdodds.com>
Co-authored-by: me <me@kentcdodds.com>
Co-authored-by: me <me@kentcdodds.com>

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Keep local validation warning-free by removing ad hoc test cleanup patterns, guarding test schema access, and applying the formatter changes validate surfaced.

Made-with: Cursor
@kentcdodds
kentcdodds merged commit e3851aa into main Mar 30, 2026
9 checks passed
@kentcdodds
kentcdodds deleted the cursor/client-library-integration-in-dynamic-loader-6277 branch April 17, 2026 00:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants