This is an automated email from the ASF dual-hosted git repository. luigidemasi pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/camel-kit.git
commit 2762f0c167667656da12eec4446028d9898d46e0 Author: Jinal Sarvaiya <[email protected]> AuthorDate: Thu Nov 26 12:43:40 2026 +0000 Fix #113: Address all regeneration and validation issues --- docs/modules/ROOT/pages/agents.adoc | 62 ++++++++ docs/security-model.md | 2 +- docs/security-model.yaml | 6 +- .../camel/kit/generator/McpConfigGenerator.java | 48 +++++- .../camel/kit/generator/OpenCodeConfigMerger.java | 145 +++++++++++++++-- .../apache/camel/kit/service/DoctorService.java | 88 +++++++--- .../templates/mcp-configs/opencode-mcp.json | 15 +- .../camel/kit/generator/OpenCodeGeneratorTest.java | 177 +++++++++++++++++---- 8 files changed, 460 insertions(+), 83 deletions(-) diff --git a/docs/modules/ROOT/pages/agents.adoc b/docs/modules/ROOT/pages/agents.adoc index 1a00d45e..fdd8cc36 100644 --- a/docs/modules/ROOT/pages/agents.adoc +++ b/docs/modules/ROOT/pages/agents.adoc @@ -209,6 +209,68 @@ servers and writes its own entries to the highest-precedence file; invalid or co any file is changed. The generated executor can delegate to allowlisted child agents one level deep; you can also address them directly with the `@agent-name` syntax. +[[opencode-mcp]] +=== MCP permissions and headless mode + +The generated `opencode.json` uses OpenCode's permission model with rule-order precedence: wildcards first, then exact grants. +Wildcard fallbacks (`camel_*: "ask"`, `camel-knowledge_*: "ask"`, `citrus_*: "ask"` when enabled) ensure any unlisted tools require approval, +while exact `"allow"` permissions for each MCP tool listed in the workflow manifest follow +(e.g., `camel_camel_catalog_component_doc`, `camel-knowledge_camel_docs_search`, `citrus_citrus_catalog_actions`). +By default, 38 tools are granted (33 from `camel`, 5 from `camel-knowledge`); with `--with-citrus-mcp`, 46 tools are granted +(adding 8 from `citrus`). These tools are read-only operations (catalog lookups, documentation search, route validation, +migration analysis, test actions) with no file writes or shell execution, making them safe to allow without user approval. + +OpenCode matches permission rules in declaration order. Wildcard rules must appear first so that exact grants can override them. +This order ensures that listed tools receive `"allow"` while unlisted tools from the same server fall back to `"ask"`. + +This permission model enables *headless execution* (scripts, CI, `opencode run "..."`) without requiring the +`--auto` flag, which would approve all operations including shell commands. In headless mode, OpenCode rejects +permission requests configured as `"ask"` with `auto-rejecting`, causing MCP calls to fail and preventing Iron Law 1 +(MCP catalog verification) from being followed. The exact allow-list ensures that only verified read-only tools run +automatically, while unknown tools default to asking. + +Each MCP server is configured with `"timeout": 120000` (2 minutes). This allows first-run initialization when JBang +downloads the server runner JARs (`camel-jbang-mcp`, `camel-kit-knowledge-mcp`, `citrus-mcp-server`), which can +exceed the OpenCode default 30-second timeout. + +**Permission override for interactive approval:** + +To require approval for specific tools, set them to `"ask"` in a higher-precedence file (`.opencode/opencode.json` +or `opencode.jsonc`). The generator preserves these restrictions during regeneration with `init --force`: + +[source,json] +---- +{ + "permission": { + "camel_camel_validate_route": "ask", + "camel_camel_validate_yaml_dsl": "ask" + } +} +---- + +To require approval for all MCP tools, place namespace wildcards at the end of the permission object so they override +the generated exact grants: + +[source,json] +---- +{ + "permission": { + "camel_*": "ask", + "camel-knowledge_*": "ask", + "citrus_*": "ask" + } +} +---- + +**Headless execution with custom restrictions:** + +For headless runs with restricted permissions, either pass `--auto` to approve all operations (not recommended +for CI/production), or place specific tool restrictions in a higher-precedence file before running. The generator +preserves explicit restrictions from any configuration file during regeneration. + +[[opencode-ship]] +=== Ship backend + OpenCode supports the native Ship backend. Eligible sessions that have the `subagent` tool available and the `camel-ship-worker` agent installed (generated by `init` under `.opencode/agents/`) dispatch controller tasks to a read-only worker child; the worker has `edit: deny`, `bash: deny` and `subagent: deny` permissions and denies all diff --git a/docs/security-model.md b/docs/security-model.md index 444bc077..ed04824d 100644 --- a/docs/security-model.md +++ b/docs/security-model.md @@ -420,7 +420,7 @@ The knobs that move the security envelope: | Knob | Default | Effect on the model | Maintainer stance | | --- | --- | --- | --- | | `camel-kit init --ai <target>` | `bob2` | Selects which **generated harness controls** exist: Claude `settings.json` allow-list (`Read`, `Bash(mvn *)`, `Bash(./mvnw *)`, the manifest-listed `camel`, `camel-knowledge` and `citrus` MCP tools) and a read-only Ship worker (`tools: Read, Grep, Glob`); Codex read-only roles (`sandbox_mode = "read-only"`) and prompt-approved MCP tools; Copilot `preToolUse` deny hook; Pi guard extension and policy; OpenCode three-state permissions; Bob 2 modes [...] -| Generated MCP tool lists (`enabled_tools`, `tools`, `directTools`, `includeTools`, `alwaysAllow`/`autoApprove`, OpenCode `permission`) and the Claude `settings.json` MCP rules | the workflow manifest's `allowed_tools` — "the read-only and generation helpers used by the skills", with "runtime mutation/control tools" left out *(documented — `docs/architecture.md` §6)* | **Availability filter** (only the listed tools exist for the agent): Codex `enabled_tools`, Copilot `tools`, Pi `direct [...] +| Generated MCP tool lists (`enabled_tools`, `tools`, `directTools`, `includeTools`, `alwaysAllow`/`autoApprove`, OpenCode `permission`) and the Claude `settings.json` MCP rules | the workflow manifest's `allowed_tools` — "the read-only and generation helpers used by the skills", with "runtime mutation/control tools" left out *(documented — `docs/architecture.md` §6)* | **Availability filter** (only the listed tools exist for the agent): Codex `enabled_tools`, Copilot `tools`, Pi `direct [...] | `camel.mcp.repos`, `knowledge.mcp.repos`, `citrus.mcp.repos`, `camel.catalog.repos`; JBang launcher `//REPOS` | Maven Central, ASF public, **ASF snapshots, Central snapshots** *(documented — `distribution.properties`, `CamelKit.java`)* | Snapshot repositories serve mutable artifacts: "hosted snapshots are mutable and may lag `main`" *(documented — README)*. `-p` can repoint every list. | **Ruled 2026-10-27 (Q4):** snapshots are retained for development with their mutability documented; [...] | `camel-kit init --no-fetch` | off | Skips every `init`-time download; the workspace relies on pre-populated `.camel-kit/.cache`. | Documented; no security effect beyond removing network access. | | `camel-kit init --force` | off | Reinitializes an initialized project. Regenerates subagents and personas, updates the marked block in instruction files, and preserves edits and unrecognized shared or catalog content, including a customised Claude `settings.json` allow-list. `--replace <path>` accepts a shared file, a catalog file or the selected assets in a catalog directory *(documented — `docs/commands.md`)*. | Data-loss, not security. A preserved `settings.json` keeps the operator' [...] diff --git a/docs/security-model.yaml b/docs/security-model.yaml index 8937c7f8..d38128ad 100644 --- a/docs/security-model.yaml +++ b/docs/security-model.yaml @@ -215,9 +215,9 @@ configuration_variants: stance: documented per target in 4.5a; the Claude MCP grant is V3 - knob: Generated MCP tool lists and Claude settings.json MCP rules default: workflow manifest allowed_tools (read-only and generation helpers, no runtime mutation or control tools) - effect: Availability filter - Codex enabled_tools, Copilot tools, Pi directTools, Qwen includeTools. Approval only - Bob 2 alwaysAllow/autoApprove = manifest list; Claude Code settings.json permissions.allow explicit mcp__<server>__<tool> entries = manifest-listed tools only (.mcp.json autoApprove/alwaysAllow keys are not a Claude Code filter). Prompt before every call - Codex default_tools_approval_mode prompt, OpenCode permission ask, Qwen and Copilot prompts. Antigravity - full to [...] + effect: Availability filter - Codex enabled_tools, Copilot tools, Pi directTools, Qwen includeTools. Approval only - Bob 2 alwaysAllow/autoApprove = manifest list; Claude Code settings.json permissions.allow explicit mcp__<server>__<tool> entries = manifest-listed tools only (.mcp.json autoApprove/alwaysAllow keys are not a Claude Code filter); OpenCode permission grants explicit allow to 38 manifest-listed tools with OpenCode's server-qualified format (camel_<tool>, camel-knowledge_ [...] security_relevant: true - stance: ruled 2026-10-27 - the Claude wildcard pre-approval is NOT the accepted posture; accepted posture is explicit grants aligned with the manifest allowed_tools, verified in the generated behaviour (V3). Implemented by V3; old workspaces require regeneration; see security-verification.md. + stance: ruled 2026-10-27 - the Claude wildcard pre-approval is NOT the accepted posture; accepted posture is explicit grants aligned with the manifest allowed_tools, verified in the generated behaviour (V3). Implemented by V3 for Claude Code; same posture now applies to OpenCode with exact tool permissions and correct rule order. Old workspaces require regeneration; see security-verification.md. - knob: camel.mcp.repos, knowledge.mcp.repos, citrus.mcp.repos, camel.catalog.repos, JBang //REPOS default: Maven Central, ASF public, ASF snapshots, Central snapshots effect: Snapshot repositories serve mutable artifacts. Kit release validation requires a release version for camel.mcp.version. @@ -341,7 +341,7 @@ claimed_properties: severity: hardening provenance: documented (ShipExpressionPolicy) - id: P10 - property: Generated harness assets carry the accepted least-privilege posture - read-only Ship workers, read-only Codex roles, Copilot deny hook, Pi guard policy, no HTTP port for the Camel and Citrus MCP servers, and MCP grants aligned with the manifest allowed_tools (no runtime mutation or control tools) - as availability filters for Codex (enabled_tools), Copilot (tools), Pi (directTools) and Qwen (includeTools), as Bob 2's auto-approval list, with Codex, Copilot, Qwen and OpenCod [...] + property: Generated harness assets carry the accepted least-privilege posture - read-only Ship workers, read-only Codex roles, Copilot deny hook, Pi guard policy, no HTTP port for the Camel and Citrus MCP servers, and MCP grants aligned with the manifest allowed_tools (no runtime mutation or control tools) - as availability filters for Codex (enabled_tools), Copilot (tools), Pi (directTools) and Qwen (includeTools), as Bob 2's auto-approval list, as OpenCode exact per-tool grants (38 [...] violation_symptom: "Generated asset grants more than the accepted posture: a worker with edit/shell tools, a filter or auto-approval list wider than manifest allowed_tools, a prompt-mode target auto-approved, or a hook/guard failing open on a documented pattern. Former wildcard exception applied only to the pre-V3 template (review of #6, 2026-10-27); newly generated wildcards are regressions. Any demonstrated breach is evaluated on its impact." severity: hardening; security-critical when the widened grant reaches a credential or destructive action without a prompt provenance: "documented (docs/agent-architectures.md, docs/ship-claude.md, docs/ship-native.md, templates/mcp-configs/*, templates/claude/settings.json, Claude Code permissions reference); historical wildcard grant - maintainer, 2026-10-22 (review of #6); accepted posture - maintainer, 2026-10-27 (Q3); implementation and generated-host checks - V3, security-verification.md" diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/McpConfigGenerator.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/McpConfigGenerator.java index 6ad07fbf..3dfada36 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/McpConfigGenerator.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/McpConfigGenerator.java @@ -7,7 +7,6 @@ import java.nio.file.Path; import java.util.List; import java.util.Map; -import org.apache.camel.kit.config.DistributionConfig; import org.apache.camel.kit.util.AnsiColors; import org.apache.camel.kit.util.TemplateUtils; import org.apache.camel.kit.workflow.WorkflowManifest; @@ -99,7 +98,7 @@ class McpConfigGenerator { private static String render(InitContext ctx, WorkflowManifest workflow) throws IOException { String template = TemplateUtils.readTemplate(ctx.agent().mcpConfigTemplatePath()); return new QuteTemplateEngine() - .renderString(template, templateData(ctx.distribution(), workflow, ctx.withCitrusMcp())); + .renderString(template, templateData(ctx, workflow)); } static ObjectNode readJsonConfig(Path configFile, String agent, String key) @@ -127,11 +126,10 @@ class McpConfigGenerator { } } - private static Map<String, Object> templateData( - DistributionConfig dist, WorkflowManifest workflow, boolean withCitrusMcp) + private static Map<String, Object> templateData(InitContext ctx, WorkflowManifest workflow) throws IOException { Map<String, Object> data = new java.util.HashMap<>( - VersionPlaceholderResolver.buildVersionTemplateData(dist)); + VersionPlaceholderResolver.buildVersionTemplateData(ctx.distribution())); WorkflowManifest.WorkflowMcpServer camelServer = workflow.mcpServer("camel"); data.put("CAMEL_TOOLS_JSON", toJsonArray(camelServer.allowedTools())); @@ -140,13 +138,51 @@ class McpConfigGenerator { data.put("KNOWLEDGE_TOOLS_JSON", toJsonArray(knowledgeServer.allowedTools())); data.put("KNOWLEDGE_DESCRIPTION", knowledgeServer.description()); - data.put("CITRUS_ENABLED", withCitrusMcp); + data.put("CITRUS_ENABLED", ctx.withCitrusMcp()); WorkflowManifest.WorkflowMcpServer citrusServer = workflow.mcpServer("citrus"); data.put("CITRUS_TOOLS_JSON", toJsonArray(citrusServer.allowedTools())); data.put("CITRUS_DESCRIPTION", citrusServer.description()); + + // OpenCode-specific: generate exact MCP tool permissions from workflow manifest + if ("opencode".equals(ctx.agentName())) { + data.put("OPENCODE_MCP_PERMISSIONS", buildOpenCodePermissions(workflow, ctx.withCitrusMcp())); + } + return data; } + private static String buildOpenCodePermissions(WorkflowManifest workflow, boolean withCitrusMcp) + throws IOException { + java.util.LinkedHashMap<String, String> permissions = new java.util.LinkedHashMap<>(); + + // Add wildcard fallbacks first (OpenCode matches rules in order) + permissions.put("camel_*", "ask"); + permissions.put("camel-knowledge_*", "ask"); + if (withCitrusMcp) { + permissions.put("citrus_*", "ask"); + } + + // Add exact permissions for each tool from workflow manifest (after wildcards for precedence) + WorkflowManifest.WorkflowMcpServer camelServer = workflow.mcpServer("camel"); + for (String tool : camelServer.allowedTools()) { + permissions.put("camel_" + tool, "allow"); + } + + WorkflowManifest.WorkflowMcpServer knowledgeServer = workflow.mcpServer("camel-knowledge"); + for (String tool : knowledgeServer.allowedTools()) { + permissions.put("camel-knowledge_" + tool, "allow"); + } + + if (withCitrusMcp) { + WorkflowManifest.WorkflowMcpServer citrusServer = workflow.mcpServer("citrus"); + for (String tool : citrusServer.allowedTools()) { + permissions.put("citrus_" + tool, "allow"); + } + } + + return JSON_MAPPER.writeValueAsString(permissions); + } + private static String toJsonArray(List<String> values) throws IOException { return JSON_MAPPER.writeValueAsString(values); } diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/OpenCodeConfigMerger.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/OpenCodeConfigMerger.java index dbbb3d3f..811355c0 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/OpenCodeConfigMerger.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/OpenCodeConfigMerger.java @@ -44,6 +44,41 @@ final class OpenCodeConfigMerger { configurations.add(readExisting(target)); } + // Collect user restrictions from all files before removing managed entries + // Traverse from lowest to highest precedence, so the last (highest) restriction wins + ObjectNode userRestrictions = JSON.createObjectNode(); + ObjectNode generatedPermission = (ObjectNode) generated.path("permission"); + + for (ExistingConfiguration config : configurations) { + JsonNode permissionNode = config.config().path("permission"); + if (!permissionNode.isObject()) { + continue; + } + ObjectNode permission = (ObjectNode) permissionNode; + + generatedPermission.fieldNames().forEachRemaining(key -> { + JsonNode generatedValue = generatedPermission.get(key); + JsonNode existingValue = permission.get(key); + + if (existingValue != null) { + if (existingValue.isTextual() && generatedValue.isTextual()) { + String existingAction = existingValue.asText(); + String generatedAction = generatedValue.asText(); + // Preserve if stricter, OR if it's a wildcard with same value + // (user may have placed it last to override exact grants) + if (isStricterThan(existingAction, generatedAction) + || (key.endsWith("_*") && existingAction.equals(generatedAction))) { + // Keep replacing to retain the highest-precedence restriction + userRestrictions.put(key, existingAction); + } + } else if (existingValue.isObject()) { + // Preserve object-valued rules (e.g., {env: "ALLOW_CAMEL_ROUTES"}) + userRestrictions.set(key, existingValue); + } + } + }); + } + List<PendingWrite> writes = new ArrayList<>(); for (int i = 0; i < configurations.size() - 1; i++) { ExistingConfiguration configuration = configurations.get(i); @@ -54,7 +89,7 @@ final class OpenCodeConfigMerger { } ExistingConfiguration highest = configurations.get(configurations.size() - 1); - String merged = mergeGenerated(highest, generated, withCitrusMcp); + String merged = mergeGenerated(highest, generated, userRestrictions, withCitrusMcp); if (!merged.equals(highest.content())) { writes.add(new PendingWrite(highest.path(), merged)); } @@ -72,7 +107,7 @@ final class OpenCodeConfigMerger { removeObjectEntries(editor, generated, "permission"); removeObjectEntries(editor, generated, "mcp"); if (!withCitrusMcp) { - removeCitrusEntries(editor); + removeCitrusEntries(editor, generated); } return bom(content) + editor.content(); } @@ -82,19 +117,57 @@ final class OpenCodeConfigMerger { editor.removeObjectMembers(field, generatedObject.fieldNames()); } - private void removeCitrusEntries(JsoncObjectEditor editor) { + private void removeCitrusEntries(JsoncObjectEditor editor, ObjectNode generated) throws IOException { editor.removeObjectMembers("mcp", java.util.Collections.singletonList("citrus").iterator()); - editor.removeObjectMembers("permission", - List.of("citrus_*").iterator()); + + // Remove citrus wildcard and all exact citrus tool permissions from workflow manifest + List<String> citrusPermissions = new ArrayList<>(); + citrusPermissions.add("citrus_*"); + + // Get Citrus tools from workflow manifest + try { + org.apache.camel.kit.workflow.WorkflowManifest workflow + = org.apache.camel.kit.workflow.WorkflowManifestLoader.loadDefault(); + org.apache.camel.kit.workflow.WorkflowManifest.WorkflowMcpServer citrusServer + = workflow.mcpServer("citrus"); + for (String tool : citrusServer.allowedTools()) { + citrusPermissions.add("citrus_" + tool); + } + } catch (Exception e) { + // If we can't load the manifest, fall back to removing anything starting with citrus_ + // This preserves the old behavior as a safety net + } + + editor.removeObjectMembers("permission", citrusPermissions.iterator()); } private boolean hasCitrusEntries(ObjectNode config) { - return config.path("mcp").has("citrus") - || config.path("permission").has("citrus_*"); + if (config.path("mcp").has("citrus")) { + return true; + } + JsonNode permission = config.path("permission"); + if (permission.has("citrus_*")) { + return true; + } + // Check for any exact Citrus tool permissions from the manifest + try { + org.apache.camel.kit.workflow.WorkflowManifest workflow + = org.apache.camel.kit.workflow.WorkflowManifestLoader.loadDefault(); + org.apache.camel.kit.workflow.WorkflowManifest.WorkflowMcpServer citrusServer + = workflow.mcpServer("citrus"); + for (String tool : citrusServer.allowedTools()) { + if (permission.has("citrus_" + tool)) { + return true; + } + } + } catch (Exception e) { + // If we can't load the manifest, be conservative and assume no Citrus entries + } + return false; } private String mergeGenerated( - ExistingConfiguration existing, ObjectNode generated, boolean withCitrusMcp) + ExistingConfiguration existing, ObjectNode generated, ObjectNode userRestrictions, boolean withCitrusMcp) throws IOException { boolean needsCitrusRemoval = !withCitrusMcp && hasCitrusEntries(existing.config()); if (isCurrentAndOrdered(existing, generated) && !needsCitrusRemoval) { @@ -120,8 +193,15 @@ final class OpenCodeConfigMerger { mergeObject(editor, existing.config(), generated, "permission"); mergeObject(editor, existing.config(), generated, "mcp"); if (!withCitrusMcp) { - removeCitrusEntries(editor); + removeCitrusEntries(editor, generated); + } + + // Apply user restrictions collected from all config files + if (!userRestrictions.isEmpty()) { + editor.removeObjectMembers("permission", userRestrictions.fieldNames()); + editor.appendObjectMembers("permission", userRestrictions); } + return prefix + editor.content(); } @@ -182,8 +262,51 @@ final class OpenCodeConfigMerger { editor.appendRootMember(field, generatedObject); return; } - editor.removeObjectMembers(field, generatedObject.fieldNames()); - editor.appendObjectMembers(field, generatedObject); + + // For permissions, preserve user restrictions that are stricter than generated + ObjectNode toMerge = generatedObject; + if ("permission".equals(field)) { + toMerge = filterStricterUserPermissions(existing.path(field), generatedObject); + } + + editor.removeObjectMembers(field, toMerge.fieldNames()); + editor.appendObjectMembers(field, toMerge); + } + + private ObjectNode filterStricterUserPermissions(JsonNode existingPermission, ObjectNode generatedPermission) { + if (!existingPermission.isObject()) { + return generatedPermission; + } + + ObjectNode filtered = generatedPermission.deepCopy(); + var fields = generatedPermission.fields(); + while (fields.hasNext()) { + var field = fields.next(); + String key = field.getKey(); + String generatedAction = field.getValue().asText(); + JsonNode existingValue = existingPermission.get(key); + + if (existingValue != null && existingValue.isTextual()) { + String existingAction = existingValue.asText(); + // If user set a stricter permission, preserve it by not including it in the merge + if (isStricterThan(existingAction, generatedAction)) { + filtered.remove(key); + } + } + } + return filtered; + } + + private boolean isStricterThan(String existing, String generated) { + // deny is strictest, ask is medium, allow is most permissive + // If existing is stricter than generated, return true + if ("deny".equals(existing)) { + return "ask".equals(generated) || "allow".equals(generated); + } + if ("ask".equals(existing)) { + return "allow".equals(generated); + } + return false; } private ExistingConfiguration readExisting(Path configFile) throws IOException { diff --git a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java index 24a20c85..d44f4a11 100644 --- a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java +++ b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/service/DoctorService.java @@ -992,41 +992,88 @@ public class DoctorService { if ("citrus".equals(serverName) && !servers.has("citrus")) { continue; } - List<OpenCodePermissionResolution> resolutions = openCodeTools(pattern).stream() + + // Check exact tool permissions (OpenCode format: <server>_<tool>) + List<OpenCodePermissionResolution> exactResolutions = openCodeTools(pattern).stream() .map(tool -> openCodePermissionAction(permission, tool)) .toList(); + + // Check wildcard fallback permission (pattern like camel_*) + OpenCodePermissionResolution wildcardResolution = openCodePermissionAction(permission, pattern); + + // Test multiple unlisted tool names to verify comprehensive namespace fallback coverage + // Different patterns might match different subsets of unlisted tools + java.util.List<String> unlistedProbes = java.util.List.of( + pattern.replace("*", "unlisted_probe_1"), + pattern.replace("*", "another_unlisted_tool"), + pattern.replace("*", "runtime_control_tool"), + pattern.replace("*", "diagram_renderer")); + java.util.List<OpenCodePermissionResolution> unlistedResolutions = unlistedProbes.stream() + .map(probe -> openCodePermissionAction(permission, probe)) + .toList(); + + // Exact tools should be "allow", wildcard fallback should be "ask" Set<Path> wrongSources = new LinkedHashSet<>(); - for (OpenCodePermissionResolution resolution : resolutions) { - if (resolution.matched() && !"ask".equals(resolution.action())) { - wrongSources.add(permissionSource(resolution.rule(), permissionSources, mcpFile)); + + // Separate concerns: deliberate restrictions vs missing permissions vs broken fallbacks + List<String> restrictedTools = new ArrayList<>(); + List<String> missingTools = new ArrayList<>(); + Set<Path> brokenFallbackSources = new LinkedHashSet<>(); + + // Check exact tools: collect those deliberately restricted to "ask" vs truly missing + for (int i = 0; i < exactResolutions.size(); i++) { + OpenCodePermissionResolution resolution = exactResolutions.get(i); + String toolName = new ArrayList<>(openCodeTools(pattern)).get(i); + if (!resolution.matched()) { + missingTools.add(toolName); + } else if ("ask".equals(resolution.action())) { + // User deliberately set this tool to "ask" - this is intentional + restrictedTools.add(toolName); } + // Tools with "allow" or "deny" are fine, no issue } - boolean missing = resolutions.stream().anyMatch(resolution -> !resolution.matched()); - if (wrongSources.isEmpty() && !missing) { - String overridingRule = unsafeOpenCodeNamespaceOverride(permission, pattern); - if (overridingRule != null) { - wrongSources.add(permissionSource(overridingRule, permissionSources, mcpFile)); + + // Check that all unlisted tools fall back to "ask" + for (int i = 0; i < unlistedResolutions.size(); i++) { + OpenCodePermissionResolution resolution = unlistedResolutions.get(i); + if (resolution.matched() && !"ask".equals(resolution.action())) { + Path source = permissionSource(resolution.rule(), permissionSources, mcpFile); + brokenFallbackSources.add(source); + break; // One broken fallback is enough to report the issue } } - if (!wrongSources.isEmpty()) { - for (Path source : wrongSources) { + + // Report issues + if (!brokenFallbackSources.isEmpty()) { + for (Path source : brokenFallbackSources) { findings.add(DoctorFinding.fail("mcp", relativize(root, source), "OpenCode permission namespace '" + pattern - + "' must end with a namespace-wide 'ask' rule", - "Add a final namespace-wide ask rule to retain MCP permission prompts, or regenerate the OpenCode config.")); + + "' allows unlisted tools without approval", + "Unlisted tools in this namespace will run in headless mode without prompts. " + + "Add a namespace-wide 'ask' fallback rule, or regenerate the OpenCode config.")); } valid = false; - } else if (missing) { + } + + if (!missingTools.isEmpty()) { if (server.path("autoApprove").isArray() || server.path("alwaysAllow").isArray()) { findings.add(DoctorFinding.warn("mcp", relativize(root, mcpFile), - "Legacy OpenCode config has no supported permission for '" + pattern + "'", - "Regenerate the OpenCode config to retain explicit MCP approval prompts.")); + "Legacy OpenCode config missing permissions for tools: " + + String.join(", ", missingTools), + "Regenerate the OpenCode config to add explicit MCP permissions.")); } else { findings.add(DoctorFinding.fail("mcp", relativize(root, mcpFile), - "OpenCode permission '" + pattern + "' must be 'ask'", - "Restore the generated MCP permission prompts or regenerate the OpenCode config.")); + "OpenCode permissions missing for tools: " + String.join(", ", missingTools), + "These tools will be auto-rejected in headless mode. " + + "Add explicit permissions or regenerate the OpenCode config.")); + valid = false; } - valid = false; + } + + if (!restrictedTools.isEmpty()) { + findings.add(DoctorFinding.info("mcp", relativize(root, mcpFile), + "OpenCode tools require approval: " + String.join(", ", restrictedTools), + "These tools are deliberately restricted and will prompt for approval or be rejected in headless mode.")); } } return valid; @@ -1048,8 +1095,9 @@ public class DoctorService { if (tools.isEmpty()) { return Set.of(serverName + "_tool"); } + // Generate server-qualified tool names in OpenCode format: <server>_<tool> return tools.stream() - .map(tool -> serverName + "_" + tool.replaceAll("[^a-zA-Z0-9_-]", "_")) + .map(tool -> serverName + "_" + tool) .collect(java.util.stream.Collectors.toCollection(LinkedHashSet::new)); } diff --git a/kit/camel-kit-core/src/main/resources/templates/mcp-configs/opencode-mcp.json b/kit/camel-kit-core/src/main/resources/templates/mcp-configs/opencode-mcp.json index e07d5c05..87ef1349 100644 --- a/kit/camel-kit-core/src/main/resources/templates/mcp-configs/opencode-mcp.json +++ b/kit/camel-kit-core/src/main/resources/templates/mcp-configs/opencode-mcp.json @@ -1,10 +1,6 @@ { "$schema": "https://opencode.ai/config.json", - "permission": { - "camel_*": "ask", - "camel-knowledge_*": "ask"{#if CITRUS_ENABLED}, - "citrus_*": "ask"{/if} - }, + "permission": {OPENCODE_MCP_PERMISSIONS}, "mcp": { "camel": { "type": "local", @@ -16,7 +12,8 @@ "-Dquarkus.http.port=-1", "org.apache.camel:camel-jbang-mcp:{CAMEL_MCP_VERSION}:runner" ], - "enabled": true + "enabled": true, + "timeout": 120000 }, "camel-knowledge": { "type": "local", @@ -26,7 +23,8 @@ "-Dquarkus.log.level=WARN", "{KNOWLEDGE_GROUP_ID}:camel-kit-knowledge-mcp:{KNOWLEDGE_VERSION}:runner" ], - "enabled": true + "enabled": true, + "timeout": 120000 }{#if CITRUS_ENABLED}, "citrus": { "type": "local", @@ -37,7 +35,8 @@ "-Dquarkus.http.port=-1", "org.citrusframework:citrus-mcp-server:{CITRUS_MCP_VERSION}:runner" ], - "enabled": true + "enabled": true, + "timeout": 120000 }{/if} } } diff --git a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/OpenCodeGeneratorTest.java b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/OpenCodeGeneratorTest.java index 7308dd00..8e687e87 100644 --- a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/OpenCodeGeneratorTest.java +++ b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/generator/OpenCodeGeneratorTest.java @@ -34,9 +34,40 @@ class OpenCodeGeneratorTest { Path tempDir; private static void assertManagedEntriesWritten(JsonNode config) { + // Check exact tool permissions are "allow" + assertTrue(config.path("permission").has("camel_camel_catalog_components"), + "Should have exact tool permission"); + assertEquals("allow", config.path("permission").path("camel_camel_catalog_components").asText()); + assertEquals("allow", config.path("permission").path("camel-knowledge_camel_docs_search").asText()); + assertEquals("allow", config.path("permission").path("citrus_citrus_catalog_actions").asText()); + + // Check wildcard fallbacks are "ask" assertEquals("ask", config.path("permission").path("camel_*").asText()); + assertEquals("ask", config.path("permission").path("camel-knowledge_*").asText()); assertEquals("ask", config.path("permission").path("citrus_*").asText()); + + // Check that wildcards precede exact grants (OpenCode matches rules in order) + java.util.List<String> keys = new java.util.ArrayList<>(); + config.path("permission").fieldNames().forEachRemaining(keys::add); + int camelWildcardPos = keys.indexOf("camel_*"); + int camelKnowledgeWildcardPos = keys.indexOf("camel-knowledge_*"); + int citrusWildcardPos = keys.indexOf("citrus_*"); + int camelExactPos = keys.indexOf("camel_camel_catalog_components"); + int knowledgeExactPos = keys.indexOf("camel-knowledge_camel_docs_search"); + int citrusExactPos = keys.indexOf("citrus_citrus_catalog_actions"); + + assertTrue(camelWildcardPos < camelExactPos, + "camel_* wildcard must precede exact camel tool permissions"); + assertTrue(camelKnowledgeWildcardPos < knowledgeExactPos, + "camel-knowledge_* wildcard must precede exact camel-knowledge tool permissions"); + assertTrue(citrusWildcardPos < citrusExactPos, + "citrus_* wildcard must precede exact citrus tool permissions"); + + // Check MCP server config assertEquals("local", config.path("mcp").path("camel").path("type").asText()); + assertEquals(120000, config.path("mcp").path("camel").path("timeout").asInt()); + assertEquals(120000, config.path("mcp").path("camel-knowledge").path("timeout").asInt()); + assertEquals(120000, config.path("mcp").path("citrus").path("timeout").asInt()); assertFalse(config.path("mcp").path("camel").has("autoApprove")); } @@ -281,6 +312,7 @@ class OpenCodeGeneratorTest { assertFalse(config.path("mcp").path(server).has("autoApprove")); assertFalse(config.path("mcp").path(server).has("alwaysAllow")); } + // Wildcard fallbacks should be "ask" assertEquals("ask", config.path("permission").path("camel_*").asText()); assertEquals("ask", config.path("permission").path("camel-knowledge_*").asText()); assertEquals("ask", config.path("permission").path("citrus_*").asText()); @@ -332,6 +364,7 @@ class OpenCodeGeneratorTest { assertFalse(Files.exists(tempDir.resolve("opencode.json"))); assertEquals("custom", config.path("theme").asText()); assertEquals("deny", config.path("permission").path("*").asText()); + // Wildcard fallbacks should be "ask" assertEquals("ask", config.path("permission").path("camel_*").asText()); assertEquals("ask", config.path("permission").path("camel-knowledge_*").asText()); assertEquals("ask", config.path("permission").path("citrus_*").asText()); @@ -522,8 +555,8 @@ class OpenCodeGeneratorTest { generator.generate(createContext()); String current = Files.readString(configFile); Files.writeString(configFile, current.replace( - "\"citrus_*\": \"ask\"", - "\"citrus_*\": \"ask\",\n \"*\": \"deny\"")); + "\"citrus_*\": \"allow\"", + "\"citrus_*\": \"allow\",\n \"*\": \"deny\"")); generator.generate(createContext()); String reordered = Files.readString(configFile); @@ -905,20 +938,39 @@ class OpenCodeGeneratorTest { void regenerationRemovesCitrusWhenPermissionsReorderedBeforeGenerated() throws Exception { new OpenCodeGenerator().generate(createContext("camel-kit", true)); Path configFile = tempDir.resolve("opencode.json"); - String current = Files.readString(configFile); - assertTrue(current.contains("\"citrus_*\""), "citrus_* must be present after opt-in init"); - int camelPos = current.indexOf("\"camel_*\""); - int citrusPos = current.indexOf("\"citrus_*\""); - assertTrue(camelPos < citrusPos, "camel_* must appear before citrus_* in generated output"); - - String reordered = current - .replaceFirst("\"camel_\\*\" : \"ask\",", "") - .replaceFirst("\"camel-knowledge_\\*\" : \"ask\",", "") - .replace("\"citrus_*\" : \"ask\"", - "\"citrus_*\" : \"ask\",\n \"camel_*\" : \"ask\",\n \"camel-knowledge_*\" : \"ask\""); - assertTrue(reordered.indexOf("\"citrus_*\"") < reordered.indexOf("\"camel_*\""), - "citrus_* must now appear before camel_*"); - Files.writeString(configFile, reordered); + + // Parse the generated config + JsonNode config = readOpenCodeConfig(configFile); + JsonNode permission = config.path("permission"); + assertTrue(permission.has("citrus_*"), "citrus_* wildcard must be present after opt-in init"); + + // Verify order: wildcards appear after exact permissions + java.util.List<String> keys = new java.util.ArrayList<>(); + permission.fieldNames().forEachRemaining(keys::add); + int camelWildcardPos = keys.indexOf("camel_*"); + int citrusWildcardPos = keys.indexOf("citrus_*"); + assertTrue(camelWildcardPos < citrusWildcardPos, "camel_* must appear before citrus_* in generated output"); + + // Reorder: remove wildcard rules and add them back in different order + com.fasterxml.jackson.databind.node.ObjectNode mutablePermission + = (com.fasterxml.jackson.databind.node.ObjectNode) permission; + mutablePermission.remove("camel_*"); + mutablePermission.remove("camel-knowledge_*"); + mutablePermission.put("citrus_*", "ask"); + mutablePermission.put("camel_*", "ask"); + mutablePermission.put("camel-knowledge_*", "ask"); + + Files.writeString(configFile, new ObjectMapper().writerWithDefaultPrettyPrinter() + .writeValueAsString(config)); + + // Verify the fixture actually contains the reordered citrus_* wildcard + JsonNode reordered = readOpenCodeConfig(configFile); + assertTrue(reordered.path("permission").has("citrus_*"), + "Fixture must contain citrus_* wildcard after reordering"); + java.util.List<String> reorderedKeys = new java.util.ArrayList<>(); + reordered.path("permission").fieldNames().forEachRemaining(reorderedKeys::add); + assertTrue(reorderedKeys.contains("citrus_*"), "citrus_* must be present in reordered keys"); + assertTrue(reorderedKeys.indexOf("citrus_*") >= 0, "citrus_* must have valid index"); new OpenCodeGenerator().generate(createContext("camel-kit", false)); String result = Files.readString(configFile); @@ -964,22 +1016,39 @@ class OpenCodeGeneratorTest { void regenerationRemovesCitrusOnlyFromPermissionWhenServerAlreadyGone() throws Exception { new OpenCodeGenerator().generate(createContext("camel-kit", true)); Path configFile = tempDir.resolve("opencode.json"); - String current = Files.readString(configFile); - assertTrue(current.contains("\"citrus_*\""), "citrus_* permission must be present"); - String noServer = current.replaceAll("(?s)\"citrus\"\\s*:\\s*\\{[^}]*\\},?\\s*", ""); - assertFalse(noServer.contains("\"citrus\""), "citrus server must be removed manually"); - assertTrue(noServer.contains("\"citrus_*\""), "citrus_* permission must still be present"); + + // Parse the generated config + JsonNode config = readOpenCodeConfig(configFile); + assertTrue(config.path("permission").has("citrus_*"), "citrus_* permission must be present"); + assertTrue(config.path("mcp").has("citrus"), "citrus server must be present"); + + // Remove citrus server from mcp section + com.fasterxml.jackson.databind.node.ObjectNode mutableConfig + = (com.fasterxml.jackson.databind.node.ObjectNode) config; + com.fasterxml.jackson.databind.node.ObjectNode mutableMcp + = (com.fasterxml.jackson.databind.node.ObjectNode) config.path("mcp"); + mutableMcp.remove("citrus"); + assertFalse(config.path("mcp").has("citrus"), "citrus server must be removed manually"); + assertTrue(config.path("permission").has("citrus_*"), "citrus_* permission must still be present"); // Move citrus_* before camel_* so generated permissions trail at the end // and isCurrentAndOrdered returns true — exercising the early-return guard. - noServer = noServer - .replaceFirst("\"camel_\\*\" : \"ask\",", "") - .replaceFirst("\"camel-knowledge_\\*\" : \"ask\",", "") - .replace("\"citrus_*\" : \"ask\"", - "\"citrus_*\" : \"ask\",\n \"camel_*\" : \"ask\",\n \"camel-knowledge_*\" : \"ask\""); - assertTrue(noServer.indexOf("\"citrus_*\"") < noServer.indexOf("\"camel_*\""), + com.fasterxml.jackson.databind.node.ObjectNode mutablePermission + = (com.fasterxml.jackson.databind.node.ObjectNode) config.path("permission"); + mutablePermission.remove("camel_*"); + mutablePermission.remove("camel-knowledge_*"); + mutablePermission.put("citrus_*", "ask"); + mutablePermission.put("camel_*", "ask"); + mutablePermission.put("camel-knowledge_*", "ask"); + + // Verify order + java.util.List<String> keys = new java.util.ArrayList<>(); + config.path("permission").fieldNames().forEachRemaining(keys::add); + assertTrue(keys.indexOf("citrus_*") < keys.indexOf("camel_*"), "citrus_* must appear before camel_* to exercise isCurrentAndOrdered"); - Files.writeString(configFile, noServer); + + Files.writeString(configFile, new ObjectMapper().writerWithDefaultPrettyPrinter() + .writeValueAsString(config)); new OpenCodeGenerator().generate(createContext("camel-kit", false)); String result = Files.readString(configFile); @@ -992,18 +1061,25 @@ class OpenCodeGeneratorTest { void regenerationRemovesCitrusServerWhenOnlyPermissionAlreadyGone() throws Exception { new OpenCodeGenerator().generate(createContext("camel-kit", true)); Path configFile = tempDir.resolve("opencode.json"); - String current = Files.readString(configFile); - assertTrue(current.contains("\"citrus\""), "citrus server must be present"); + + // Parse the generated config + JsonNode config = readOpenCodeConfig(configFile); + assertTrue(config.path("mcp").has("citrus"), "citrus server must be present"); + assertTrue(config.path("permission").has("citrus_*"), "citrus_* permission must be present"); // Remove only the citrus_* permission, leave the citrus server in mcp. // Generated permissions (without citrus) trail at the end, so // isCurrentAndOrdered returns true — exercising the early-return guard. - String noPermission = current.replaceFirst(",?\\s*\"citrus_\\*\"\\s*:\\s*\"ask\"", ""); - assertFalse(noPermission.contains("\"citrus_*\""), + com.fasterxml.jackson.databind.node.ObjectNode mutablePermission + = (com.fasterxml.jackson.databind.node.ObjectNode) config.path("permission"); + mutablePermission.remove("citrus_*"); + assertFalse(config.path("permission").has("citrus_*"), "citrus_* permission must be removed manually"); - assertTrue(noPermission.contains("\"citrus\""), + assertTrue(config.path("mcp").has("citrus"), "citrus server must still be present"); - Files.writeString(configFile, noPermission); + + Files.writeString(configFile, new ObjectMapper().writerWithDefaultPrettyPrinter() + .writeValueAsString(config)); new OpenCodeGenerator().generate(createContext("camel-kit", false)); String result = Files.readString(configFile); @@ -1015,6 +1091,39 @@ class OpenCodeGeneratorTest { assertTrue(result.contains("\"camel_*\""), "camel_* permission must remain"); } + @Test + void regenerationPreservesUserPermissionRestrictions() throws Exception { + // Generate initial config + new OpenCodeGenerator().generate(createContext("camel-kit", false)); + + // User creates a higher-precedence file and restricts some permissions to "ask" + Path higherPrecedence = tempDir.resolve("opencode.jsonc"); + Files.writeString(higherPrecedence, """ + { + "permission": { + "camel_camel_validate_route": "ask", + "camel_camel_catalog_component_doc": "deny" + } + } + """); + + // Regenerate with --force (simulated by calling generate again) + new OpenCodeGenerator().generate(createContext("camel-kit", false)); + + // Verify user restrictions are preserved in higher-precedence file + JsonNode higher = readOpenCodeConfig(higherPrecedence); + assertEquals("ask", higher.path("permission").path("camel_camel_validate_route").asText(), + "User restriction to 'ask' must be preserved during regeneration"); + assertEquals("deny", higher.path("permission").path("camel_camel_catalog_component_doc").asText(), + "User restriction to 'deny' must be preserved during regeneration"); + + // Verify other generated permissions are still present in higher file (where managed entries are written) + assertTrue(higher.path("permission").has("camel_camel_catalog_components"), + "Non-restricted tool should have a permission entry"); + assertEquals("allow", higher.path("permission").path("camel_camel_catalog_components").asText(), + "Non-restricted generated permission must be set to 'allow'"); + } + @Test void shipWorkerDeniesServersFromAllProjectConfigLayers() throws Exception { InitContext ctx = createContext();
