Compare commits

...

8 Commits

Author SHA1 Message Date
opencode-agent[bot] 7d97c4c040 refactor(cli): split mcp add url and command parsing 2026-06-01 05:05:37 +00:00
opencode-agent[bot] 8e0bceaea9 refactor(cli): require mcp command separator 2026-06-01 04:57:16 +00:00
opencode-agent[bot] 010d50e993 refactor(cli): keep mcp add yargs internals local 2026-06-01 04:47:09 +00:00
opencode-agent[bot] 7f9fbac33c refactor(cli): simplify mcp add options 2026-06-01 04:43:57 +00:00
opencode-agent[bot] ebb101bd54 refactor(cli): align mcp add args help 2026-06-01 04:34:11 +00:00
opencode-agent[bot] 2ca7478b8a feat(cli): support inline mcp add args 2026-06-01 04:23:42 +00:00
Aiden Cline a9c115c220 refactor(opencode): simplify provider setup flow (#30173) 2026-05-31 23:17:57 -05:00
Aiden Cline 917a36abc3 refactor(opencode): inline local provider helpers (#30169) 2026-05-31 22:59:44 -05:00
5 changed files with 323 additions and 71 deletions
+173 -8
View File
@@ -1,5 +1,5 @@
import { cmd } from "./cmd"
import { effectCmd } from "../effect-cmd"
import { effectCmd, fail } from "../effect-cmd"
import { Cause } from "effect"
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
@@ -55,6 +55,24 @@ function isMcpRemote(config: McpEntry): config is McpRemote {
return isMcpConfigured(config) && config.type === "remote"
}
type McpAddArgs = {
name?: string
args?: string[]
type?: "local" | "remote"
env?: string[]
header?: string[]
global?: boolean
}
type InlineMcpAdd = {
name?: string
positional: string[]
command: string[]
type?: "local" | "remote"
env?: string[]
header?: string[]
}
function configuredServers(config: Config.Info) {
return Object.entries(config.mcp ?? {}).filter((entry): entry is [string, McpConfigured] => isMcpConfigured(entry[1]))
}
@@ -436,27 +454,79 @@ async function addMcpToConfig(name: string, mcpConfig: ConfigMCP.Info, configPat
}
export const McpAddCommand = effectCmd({
command: "add",
command: "add [name] [args...]",
describe: "add an MCP server",
handler: Effect.fn("Cli.mcp.add")(function* () {
builder: (yargs) =>
yargs
.positional("name", {
describe: "name of the MCP server",
type: "string",
})
.positional("args", {
describe: "URL for remote servers",
type: "string",
array: true,
default: [],
})
.option("type", {
describe: "server type: local or remote",
type: "string",
choices: ["local", "remote"] as const,
})
.option("env", {
describe: "environment variable for local servers (KEY=VALUE)",
type: "string",
array: true,
})
.option("header", {
describe: "HTTP header for remote servers (KEY=VALUE or 'KEY: VALUE')",
type: "string",
array: true,
})
.option("global", {
alias: ["g"],
describe: "save to global config",
type: "boolean",
}).epilogue(`Usage:
opencode mcp add <name> -- <command> [args...] (local MCP server)
opencode mcp add <name> --env KEY=VALUE -- <command> [args...] (local MCP server with env vars)
opencode mcp add <name> <url> (remote MCP server)
opencode mcp add <name> --header KEY=VALUE <url> (remote MCP server with headers)
opencode mcp add <name> --global <url> (save to global config)
Examples:
opencode mcp add context7 -- npx -y @upstash/context7-mcp
opencode mcp add local-env --env FOO=bar -- node server.js
opencode mcp add sg --header Authorization=token https://sg.example/mcp
opencode mcp add hugging-face https://huggingface.co/mcp`),
handler: Effect.fn("Cli.mcp.add")(function* (input) {
const maybeCtx = yield* InstanceRef
if (!maybeCtx) return yield* Effect.die("InstanceRef not provided")
const ctx = maybeCtx
const inlineConfig = parseInlineMcpAdd({
name: input.name,
positional: input.args ?? [],
command: input["--"] ?? [],
type: input.type,
env: input.env,
header: input.header,
})
if (inlineConfig && "error" in inlineConfig) return yield* fail(inlineConfig.error)
yield* Effect.promise(async () => {
UI.empty()
prompts.intro("Add MCP server")
const project = ctx.project
// Resolve config paths eagerly for hints
const [projectConfigPath, globalConfigPath] = await Promise.all([
resolveConfigPath(ctx.worktree),
resolveConfigPath(Global.Path.config, true),
])
// Determine scope
let configPath = globalConfigPath
if (project.vcs === "git") {
const configPath = await (async () => {
if (input.global) return globalConfigPath
if (inlineConfig) return project.vcs === "git" ? projectConfigPath : globalConfigPath
if (project.vcs !== "git") return globalConfigPath
const scopeResult = await prompts.select({
message: "Location",
options: [
@@ -473,7 +543,14 @@ export const McpAddCommand = effectCmd({
],
})
if (prompts.isCancel(scopeResult)) throw new UI.CancelledError()
configPath = scopeResult
return scopeResult
})()
if (inlineConfig) {
await addMcpToConfig(inlineConfig.name, inlineConfig.config, configPath)
prompts.log.success(`MCP server "${inlineConfig.name}" added to ${configPath}`)
prompts.outro("MCP server added successfully")
return
}
const name = await prompts.text({
@@ -599,6 +676,94 @@ export const McpAddCommand = effectCmd({
}),
})
function parseInlineMcpAdd(
input: InlineMcpAdd,
): { name: string; config: ConfigMCP.Info } | { error: string } | undefined {
if (!hasInlineMcpAdd(input)) return undefined
const name = input.name?.trim()
if (!name) return { error: "MCP server name is required" }
const result = input.command.length > 0 ? parseInlineLocalMcp(input) : parseInlineRemoteMcp(input)
if ("error" in result) return result
return { name, config: result.config }
}
function hasInlineMcpAdd(input: InlineMcpAdd) {
return !!(
input.name ||
input.positional.length > 0 ||
input.command.length > 0 ||
input.type ||
input.env?.length ||
input.header?.length
)
}
function parseInlineLocalMcp(input: InlineMcpAdd): { config: ConfigMCP.Info } | { error: string } {
if (input.positional.length > 0) return { error: "Remote URL arguments cannot be combined with -- <command>" }
if (input.type === "remote") return { error: "-- <command> can only be used with --type local" }
if (input.header?.length) return { error: "--header can only be used with remote MCP servers" }
const environment = parseEnv(input.env)
if ("error" in environment) return environment
return {
config: {
type: "local",
command: input.command,
...(environment.value && { environment: environment.value }),
},
}
}
function parseInlineRemoteMcp(input: InlineMcpAdd): { config: ConfigMCP.Info } | { error: string } {
if (input.type === "local" || input.env?.length) return { error: "Local MCP commands must be passed after --" }
if (input.positional.length === 0) return { error: "URL or command is required" }
const wantsRemote = input.type === "remote" || !!input.header?.length
if (input.positional.length !== 1) {
return {
error: wantsRemote ? "Remote MCP servers require exactly one URL" : "Local MCP commands must be passed after --",
}
}
if (!URL.canParse(input.positional[0])) {
return { error: wantsRemote ? "Remote MCP server URL is invalid" : "Local MCP commands must be passed after --" }
}
const headers = parseHeader(input.header)
if ("error" in headers) return headers
return {
config: {
type: "remote",
url: input.positional[0],
...(headers.value && { headers: headers.value }),
},
}
}
function parseEnv(entries?: string[]): { value?: Record<string, string> } | { error: string } {
if (!entries?.length) return {}
const parsed = entries.map((entry) => {
const index = entry.indexOf("=")
const key = entry.slice(0, index).trim()
if (index <= 0 || !key) return { error: "--env must be in KEY=VALUE format" }
return { key, value: entry.slice(index + 1) }
})
const invalid = parsed.find((entry): entry is { error: string } => "error" in entry)
if (invalid) return invalid
return { value: Object.fromEntries(parsed.map((entry) => [entry.key, entry.value])) }
}
function parseHeader(entries?: string[]): { value?: Record<string, string> } | { error: string } {
if (!entries?.length) return {}
const parsed = entries.map((entry) => {
const colon = entry.indexOf(":")
const equals = entry.indexOf("=")
const index = colon === -1 ? equals : equals === -1 ? colon : Math.min(colon, equals)
const key = entry.slice(0, index).trim()
if (index <= 0 || !key) return { error: "--header must be in KEY=VALUE or 'KEY: VALUE' format" }
return { key, value: entry.slice(index + 1).trim() }
})
const invalid = parsed.find((entry): entry is { error: string } => "error" in entry)
if (invalid) return invalid
return { value: Object.fromEntries(parsed.map((entry) => [entry.key, entry.value])) }
}
export const McpDebugCommand = effectCmd({
command: "debug <name>",
describe: "debug OAuth connection for an MCP server",
+32 -56
View File
@@ -3,13 +3,13 @@ import fuzzysort from "fuzzysort"
import { Config } from "@/config/config"
import { mapValues, mergeDeep, omit, pickBy, sortBy } from "remeda"
import { NoSuchModelError, type Provider as SDK } from "ai"
import * as Log from "@opencode-ai/core/util/log"
import { Log } from "@opencode-ai/core/util/log"
import { Npm } from "@opencode-ai/core/npm"
import { Hash } from "@opencode-ai/core/util/hash"
import { Plugin } from "../plugin"
import { serviceUse } from "@opencode-ai/core/effect/service-use"
import { type LanguageModelV3 } from "@ai-sdk/provider"
import * as ModelsDev from "@opencode-ai/core/models-dev"
import { ModelsDev } from "@opencode-ai/core/models-dev"
import { Auth } from "../auth"
import { Env } from "../env"
import { InstallationVersion } from "@opencode-ai/core/installation/version"
@@ -24,7 +24,7 @@ import { EffectPromise } from "@/effect/promise"
import { AppFileSystem } from "@opencode-ai/core/filesystem"
import { isRecord } from "@/util/record"
import { optionalOmitUndefined } from "@opencode-ai/core/schema"
import * as ProviderTransform from "./transform"
import { ProviderTransform } from "./transform"
import { ProviderV2 } from "@opencode-ai/core/provider"
import { ModelStatus } from "./model-status"
import { RuntimeFlags } from "@/effect/runtime-flags"
@@ -32,11 +32,6 @@ import { ProviderError } from "./error"
const log = Log.create({ service: "provider" })
const OPENAI_HEADER_TIMEOUT_DEFAULT = 10_000
function shouldUseCopilotResponsesApi(modelID: string): boolean {
const match = /^gpt-(\d+)/.exec(modelID)
if (!match) return false
return Number(match[1]) >= 5 && !modelID.startsWith("gpt-5-mini")
}
function wrapSSE(res: Response, ms: number, ctl: AbortController) {
if (typeof ms !== "number" || ms <= 0) return res
@@ -152,10 +147,6 @@ type CustomDep = {
get: (key: string) => Effect.Effect<string | undefined>
}
function useLanguageModel(sdk: any) {
return sdk.responses === undefined && sdk.chat === undefined
}
function selectAzureLanguageModel(sdk: any, modelID: string, useChat: boolean) {
if (useChat && sdk.chat) return sdk.chat(modelID)
if (sdk.responses) return sdk.responses(modelID)
@@ -218,8 +209,10 @@ function custom(dep: CustomDep): Record<string, CustomLoader> {
Effect.succeed({
autoload: false,
async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
if (useLanguageModel(sdk)) return sdk.languageModel(modelID)
return shouldUseCopilotResponsesApi(modelID) ? sdk.responses(modelID) : sdk.chat(modelID)
if (sdk.responses === undefined && sdk.chat === undefined) return sdk.languageModel(modelID)
const match = /^gpt-(\d+)/.exec(modelID)
if (match && Number(match[1]) >= 5 && !modelID.startsWith("gpt-5-mini")) return sdk.responses(modelID)
return sdk.chat(modelID)
},
options: {},
}),
@@ -582,11 +575,7 @@ function custom(dep: CustomDep): Record<string, CustomLoader> {
const instanceUrl = (yield* dep.get("GITLAB_INSTANCE_URL")) || "https://gitlab.com"
const auth = yield* dep.auth(input.id)
const apiKey = yield* Effect.sync(() => {
if (auth?.type === "oauth") return auth.access
if (auth?.type === "api") return auth.key
return undefined
})
const apiKey = auth?.type === "oauth" ? auth.access : auth?.type === "api" ? auth.key : undefined
const token = apiKey ?? (yield* dep.get("GITLAB_TOKEN"))
const providerConfig = (yield* dep.config()).provider?.["gitlab"]
@@ -734,12 +723,7 @@ function custom(dep: CustomDep): Record<string, CustomLoader> {
},
}
const apiKey = yield* Effect.gen(function* () {
const envToken = env["CLOUDFLARE_API_KEY"]
if (envToken) return envToken
if (auth?.type === "api") return auth.key
return undefined
})
const apiKey = env["CLOUDFLARE_API_KEY"] || (auth?.type === "api" ? auth.key : undefined)
return {
autoload: !!apiKey,
@@ -785,12 +769,8 @@ function custom(dep: CustomDep): Record<string, CustomLoader> {
}
// Get API token from env or auth - required for authenticated gateways
const apiToken = yield* Effect.gen(function* () {
const envToken = env["CLOUDFLARE_API_TOKEN"] || env["CF_AIG_TOKEN"]
if (envToken) return envToken
if (auth?.type === "api") return auth.key
return undefined
})
const apiToken =
env["CLOUDFLARE_API_TOKEN"] || env["CF_AIG_TOKEN"] || (auth?.type === "api" ? auth.key : undefined)
if (!apiToken) {
throw new Error(
@@ -1171,18 +1151,15 @@ export function fromModelsDevProvider(provider: ModelsDev.Provider): Info {
}
}
function suggestionModelIDs(provider: Info | undefined, enableExperimentalModels: boolean) {
if (!provider) return []
return Object.keys(provider.models).filter((id) => {
const model = provider.models[id]
if (model.status === "deprecated") return false
if (model.status === "alpha" && !enableExperimentalModels) return false
return true
})
}
function modelSuggestions(provider: Info | undefined, modelID: ProviderV2.ModelID, enableExperimentalModels: boolean) {
const available = suggestionModelIDs(provider, enableExperimentalModels)
const available = provider
? Object.keys(provider.models).filter((id) => {
const model = provider.models[id]
if (model.status === "deprecated") return false
if (model.status === "alpha" && !enableExperimentalModels) return false
return true
})
: []
const fuzzy = fuzzysort.go(modelID, available, { limit: 3, threshold: -10000 }).map((m) => m.target)
if (fuzzy.length) return fuzzy
const query = modelID
@@ -1681,15 +1658,15 @@ export const layer = Layer.effect(
return loaded as SDK
}
let installedPath: string
if (!model.api.npm.startsWith("file://")) {
const installedPath = await (async () => {
if (model.api.npm.startsWith("file://")) {
log.info("loading local provider", { pkg: model.api.npm })
return model.api.npm
}
const item = await Npm.add(model.api.npm)
if (!item.entrypoint) throw new Error(`Package ${model.api.npm} has no import entrypoint`)
installedPath = item.entrypoint
} else {
log.info("loading local provider", { pkg: model.api.npm })
installedPath = model.api.npm
}
return item.entrypoint
})()
// `installedPath` is a local entry path or an existing `file://` URL. Normalize
// only path inputs so Node on Windows accepts the dynamic import.
@@ -1788,7 +1765,7 @@ export const layer = Layer.effect(
const provider = s.providers[providerID]
if (!provider) return undefined
let priority = [
const defaultPriority = [
"claude-haiku-4-5",
"claude-haiku-4.5",
"3-5-haiku",
@@ -1797,12 +1774,11 @@ export const layer = Layer.effect(
"gemini-2.5-flash",
"gpt-5-nano",
]
if (providerID.startsWith("opencode")) {
priority = ["gpt-5-nano"]
}
if (providerID.startsWith("github-copilot")) {
priority = ["gpt-5-mini", "claude-haiku-4.5", ...priority]
}
const priority = providerID.startsWith("opencode")
? ["gpt-5-nano"]
: providerID.startsWith("github-copilot")
? ["gpt-5-mini", "claude-haiku-4.5", ...defaultPriority]
: defaultPriority
for (const item of priority) {
if (providerID === ProviderV2.ID.amazonBedrock) {
const crossRegionPrefixes = ["global.", "us.", "eu."]
@@ -27,11 +27,11 @@ exports[`opencode CLI help-text snapshots every documented command emits stable
manage MCP (Model Context Protocol) servers
Commands:
opencode mcp add add an MCP server
opencode mcp list list MCP servers and their status [aliases: ls]
opencode mcp auth [name] authenticate with an OAuth-enabled MCP server
opencode mcp logout [name] remove OAuth credentials for an MCP server
opencode mcp debug <name> debug OAuth connection for an MCP server
opencode mcp add [name] [args...] add an MCP server
opencode mcp list list MCP servers and their status [aliases: ls]
opencode mcp auth [name] authenticate with an OAuth-enabled MCP server
opencode mcp logout [name] remove OAuth credentials for an MCP server
opencode mcp debug <name> debug OAuth connection for an MCP server
Options:
-h, --help show help [boolean]
@@ -425,16 +425,37 @@ Options:
`;
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode mcp add --help 1`] = `
"opencode mcp add
"opencode mcp add [name] [args...]
add an MCP server
Positionals:
name name of the MCP server [string]
args URL for remote servers [array] [default: []]
Options:
-h, --help show help [boolean]
-v, --version show version number [boolean]
--print-logs print logs to stderr [boolean]
--log-level log level [string] [choices: "DEBUG", "INFO", "WARN", "ERROR"]
--pure run without external plugins [boolean]"
--pure run without external plugins [boolean]
--type server type: local or remote [string] [choices: "local", "remote"]
--env environment variable for local servers (KEY=VALUE) [array]
--header HTTP header for remote servers (KEY=VALUE or 'KEY: VALUE') [array]
-g, --global save to global config [boolean]
Usage:
opencode mcp add <name> -- <command> [args...] (local MCP server)
opencode mcp add <name> --env KEY=VALUE -- <command> [args...] (local MCP server with env vars)
opencode mcp add <name> <url> (remote MCP server)
opencode mcp add <name> --header KEY=VALUE <url> (remote MCP server with headers)
opencode mcp add <name> --global <url> (save to global config)
Examples:
opencode mcp add context7 -- npx -y @upstash/context7-mcp
opencode mcp add local-env --env FOO=bar -- node server.js
opencode mcp add sg --header Authorization=token https://sg.example/mcp
opencode mcp add hugging-face https://huggingface.co/mcp"
`;
exports[`opencode CLI help-text snapshots every documented command emits stable help text: opencode mcp auth --help 1`] = `
+72
View File
@@ -0,0 +1,72 @@
import { describe, expect } from "bun:test"
import { Effect } from "effect"
import path from "node:path"
import { cliIt } from "../lib/cli-process"
describe("opencode mcp", () => {
cliIt.live(
"adds MCP servers from inline arguments",
({ home, opencode }) =>
Effect.gen(function* () {
const result = yield* opencode.spawn([
"mcp",
"add",
"github",
"https://api.githubcopilot.com/mcp",
"--type",
"remote",
"--header",
"Authorization: Bearer test-token",
"--global",
])
opencode.expectExit(result, 0, "opencode mcp add remote")
expect(yield* Effect.promise(() => Bun.file(path.join(home, ".config/opencode/opencode.json")).json())).toEqual(
{
mcp: {
github: {
type: "remote",
url: "https://api.githubcopilot.com/mcp",
headers: {
Authorization: "Bearer test-token",
},
},
},
},
)
const local = yield* opencode.spawn([
"mcp",
"add",
"everything",
"--env",
"FOO=bar",
"--global",
"--",
"npx",
"-y",
"@modelcontextprotocol/server-everything",
])
opencode.expectExit(local, 0, "opencode mcp add local")
expect(
yield* Effect.promise(() => Bun.file(path.join(home, ".config/opencode/opencode.json")).json()),
).toMatchObject({
mcp: {
everything: {
type: "local",
command: ["npx", "-y", "@modelcontextprotocol/server-everything"],
environment: {
FOO: "bar",
},
},
},
})
const missingSeparator = yield* opencode.spawn(["mcp", "add", "bad-local", "node", "server.js", "--global"])
expect(missingSeparator.exitCode).not.toBe(0)
expect(missingSeparator.stderr).toContain("Local MCP commands must be passed after --")
}),
120_000,
)
})
@@ -44,6 +44,24 @@ You can also disable a server by setting `enabled` to `false`. This is useful if
---
## CLI
You can add MCP servers from the command line with `opencode mcp add`.
```bash
# Local server
opencode mcp add mcp_everything -- npx -y @modelcontextprotocol/server-everything
# Remote server
opencode mcp add github https://api.githubcopilot.com/mcp \
--type remote \
--header "Authorization: Bearer YOUR_GITHUB_PAT"
```
Use `--env KEY=VALUE` for local server environment variables and repeat it for multiple values. Use `--global` to save to global config.
---
### Overriding remote defaults
Organizations can provide default MCP servers via their `.well-known/opencode` endpoint. These servers may be disabled by default, allowing users to opt-in to the ones they need.