Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ The GitHub preset pins `ghcr.io/github/github-mcp-server:v1.5.0`. To upgrade saf

Claude can call `miftah_list_profiles`, `miftah_current_profile`, `miftah_use_profile`, `miftah_profile_info`, `miftah_health`, `miftah_validate_config`, `miftah_list_upstream_tools`, `miftah_restart_profile`, and `miftah_route_preview`. Upstream tools are exposed unchanged unless they collide with a reserved `miftah_` name.

For account bundles, define `upstreams` instead of `upstream`. Tools are exposed as `<upstream>__<tool>` (for example `github__search_issues`) and each profile can provide per-upstream environment or header overrides. See `examples/multi-upstream.miftah.json`.
For account bundles, define `upstreams` instead of `upstream`. Tools are exposed as `<upstream>__<tool>` (for example `github__search_issues`) and each profile can provide per-upstream environment or header overrides. Resources and prompts are available only when the bundle has exactly one upstream; multi-entry bundles intentionally omit them until namespaced aggregation exists. `miftah_health` reports this availability. See `examples/multi-upstream.miftah.json`.

## Routing and safety

Expand Down Expand Up @@ -163,7 +163,7 @@ Use `miftah doctor` to inspect config and upstream readiness without printing pr

## Current boundaries

The current experimental code implements local STDIO and remote HTTP/SSE upstream clients, profile switching, hybrid routing rules, policies, tools/resources/prompts proxying, in-memory process/session caching, redacted JSONL audit logging, and a packageable CLI. Unsupported lifecycle tuning, persisted state, UI, routing plugins, profile matchers, and configurable tool namespaces are rejected with `UNSUPPORTED_CONFIG_OPTION` rather than silently ignored.
The current experimental code implements local STDIO and remote HTTP/SSE upstream clients, profile switching, hybrid routing rules, policies, namespaced tools for account bundles, resources/prompts proxying for a standard or sole named upstream, in-memory process/session caching, redacted JSONL audit logging, and a packageable CLI. Resources and prompts are intentionally unavailable for zero- or multi-entry `upstreams` bundles. Unsupported lifecycle tuning, persisted state, UI, routing plugins, profile matchers, and configurable tool namespaces are rejected with `UNSUPPORTED_CONFIG_OPTION` rather than silently ignored.

## License

Expand Down
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ MCP client

The public server is built with the official `@modelcontextprotocol/sdk` `Server` and `StdioServerTransport`. Each profile gets an SDK `Client` and `StdioClientTransport` on first use. A single-flight start map prevents concurrent calls from launching duplicate processes. The wrapper captures the profile at routing time, so a later profile switch cannot change an in-flight call.

The server advertises management tools plus tools discovered from the active profile. Resources and prompts are proxied through the same profile. Reserved management tool names are protected; the default collision strategy prefixes a conflicting upstream name with `upstream_`.
The server advertises management tools plus tools discovered from the active profile. A standard `upstream` and a named `upstreams` map with exactly one entry proxy resources and prompts through that sole upstream. A zero-entry map and a map with two or more entries omit the MCP `resources` and `prompts` capabilities and do not register their handlers; direct resource or prompt requests then receive the standard `-32601` method-not-found response. This prevents Miftah from accidentally selecting the first upstream when aggregation and namespacing are unavailable. `miftah_health` reports `resourcePromptProxy` availability and its reason, which is also included in the server instructions when disabled. Reserved management tool names are protected; the default collision strategy prefixes a conflicting upstream name with `upstream_`.

Configuration and runtime concerns are intentionally separate:

Expand Down
2 changes: 1 addition & 1 deletion docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ miftah schema > miftah.schema.json

Required fields are `version: "1"`, `name`, `defaultProfile`, `profiles`, and either `upstream` or `upstreams`. A local STDIO upstream has `transport`, `command`, optional `args`, `env`, and `cwd`.

With `upstreams`, each profile may override `env`, `headers`, `args`, or `cwd` under a named upstream. Miftah namespaces discovered tools as `<upstream>__<tool>` so one wrapper can safely expose several providers.
With `upstreams`, each profile may override `env`, `headers`, `args`, or `cwd` under a named upstream. Miftah namespaces discovered tools as `<upstream>__<tool>` so one wrapper can safely expose several providers. Resources and prompts are proxied only when `upstreams` contains exactly one entry; zero-entry and multi-entry bundles omit those capabilities and their handlers rather than choosing an upstream. Use tools or a wrapper with a single upstream for resources and prompts while namespaced aggregation is deferred.

Profile `env` values can reference `${ENV_NAME}` or `secretref:env://ENV_NAME`. Put dotenv paths in `secrets.envFiles`; paths are resolved relative to the config file. Profile descriptions, tags, policy names, and upstream-specific `args` and `cwd` overrides are non-secret. Per-upstream `env` and `headers` values may contain credentials and use the same secret-resolution and redaction safeguards as profile-level values.

Expand Down
103 changes: 70 additions & 33 deletions src/mcp/server/miftah-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,27 +52,45 @@ function textResult(text: string, isError = false): CallToolResult {
return { content: [{ type: "text", text }], ...(isError ? { isError: true } : {}) };
}

interface ResourcePromptProxyAvailable {
available: true;
upstreamName?: string;
}

interface ResourcePromptProxyUnavailable {
available: false;
reason: string;
}

type ResourcePromptProxyAvailability = ResourcePromptProxyAvailable | ResourcePromptProxyUnavailable;

export class MiftahServer {
readonly server: Server;
private readonly routing: RoutingEngine;
private readonly policy: PolicyEngine;
private readonly audit?: AuditLogger;
private readonly resourcePromptProxy: ResourcePromptProxyAvailability;
private toolMap = new Map<string, { name: string; upstreamName?: string }>();

constructor(
private readonly config: MiftahConfig,
private readonly profiles: ProfileManager,
private readonly upstreams: UpstreamProcessManager | MultiUpstreamProcessManager
) {
this.resourcePromptProxy = this.resourcePromptProxyAvailability();
this.server = new Server(
{ name: `miftah-${config.name}`, version: "0.1.0" },
{
capabilities: {
tools: {},
resources: {},
prompts: {}
...(this.resourcePromptProxy.available ? { resources: {}, prompts: {} } : {})
},
instructions: "Miftah wraps an upstream MCP and routes requests through local credential profiles."
instructions: [
"Miftah wraps an upstream MCP and routes requests through local credential profiles.",
...(this.resourcePromptProxy.available
? []
: [this.resourcePromptProxy.reason])
].join(" ")
}
);
this.routing = new RoutingEngine(config.routing, profiles.current().activeProfile, config.defaultProfile);
Expand Down Expand Up @@ -129,39 +147,42 @@ export class MiftahServer {
return this.handleUpstreamTool(name, args);
});

this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
const session = await this.upstreams.get(this.profiles.current().activeProfile);
return session.listResources();
});
if (this.resourcePromptProxy.available) {
const upstreamName = this.resourcePromptProxy.upstreamName;
this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
const session = await this.upstreams.get(this.profiles.current().activeProfile, upstreamName);
return session.listResources();
});

this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
try {
const session = await this.upstreams.get(this.profiles.current().activeProfile);
return redactSecrets(await session.readResource(request.params), this.upstreams.getSecretValues());
} catch (error) {
throw new Error(
redactSecrets(error instanceof Error ? error.message : String(error), this.upstreams.getSecretValues()),
{ cause: error }
);
}
});
this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
try {
const session = await this.upstreams.get(this.profiles.current().activeProfile, upstreamName);
return redactSecrets(await session.readResource(request.params), this.upstreams.getSecretValues());
} catch (error) {
throw new Error(
redactSecrets(error instanceof Error ? error.message : String(error), this.upstreams.getSecretValues()),
{ cause: error }
);
}
});

this.server.setRequestHandler(ListPromptsRequestSchema, async () => {
const session = await this.upstreams.get(this.profiles.current().activeProfile);
return session.listPrompts();
});
this.server.setRequestHandler(ListPromptsRequestSchema, async () => {
const session = await this.upstreams.get(this.profiles.current().activeProfile, upstreamName);
return session.listPrompts();
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
try {
const session = await this.upstreams.get(this.profiles.current().activeProfile);
return redactSecrets(await session.getPrompt(request.params), this.upstreams.getSecretValues());
} catch (error) {
throw new Error(
redactSecrets(error instanceof Error ? error.message : String(error), this.upstreams.getSecretValues()),
{ cause: error }
);
}
});
this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
try {
const session = await this.upstreams.get(this.profiles.current().activeProfile, upstreamName);
return redactSecrets(await session.getPrompt(request.params), this.upstreams.getSecretValues());
} catch (error) {
throw new Error(
redactSecrets(error instanceof Error ? error.message : String(error), this.upstreams.getSecretValues()),
{ cause: error }
);
}
});
}
}

private async handleUpstreamTool(name: string, args: Record<string, unknown>): Promise<CallToolResult> {
Expand Down Expand Up @@ -258,6 +279,9 @@ export class MiftahServer {
JSON.stringify({
configValid: true,
activeProfile: this.profiles.current().activeProfile,
resourcePromptProxy: this.resourcePromptProxy.available
? { available: true }
: { available: false, reason: this.resourcePromptProxy.reason },
upstreams: this.upstreams.listHealth()
})
);
Expand Down Expand Up @@ -302,6 +326,19 @@ export class MiftahServer {
return [undefined];
}

private resourcePromptProxyAvailability(): ResourcePromptProxyAvailability {
if (!(this.upstreams instanceof MultiUpstreamProcessManager)) return { available: true };
const upstreamNames = this.upstreams.listUpstreams();
if (upstreamNames.length === 1) return { available: true, upstreamName: upstreamNames[0] };
if (upstreamNames.length === 0) {
return { available: false, reason: "No upstream is configured, so resource and prompt proxying is unavailable." };
}
return {
available: false,
reason: "Resource and prompt proxying is unavailable for multi-upstream bundles until namespaced aggregation is available."
};
}

private async writeAudit(event: Parameters<AuditLogger["log"]>[0]): Promise<void> {
if (this.audit) await this.audit.log(redactSecrets(event, this.upstreams.getSecretValues()));
}
Expand Down
10 changes: 9 additions & 1 deletion src/upstream/multi-upstream-process-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Tool } from "@modelcontextprotocol/sdk/types.js";
import type { MiftahConfig, ProfileConfig } from "../config/types.js";
import { UpstreamProcessManager, type UpstreamHealth, type UpstreamManagerOptions } from "./upstream-process-manager.js";
import { UpstreamSession } from "./upstream-session.js";
import { MiftahError } from "../utils/errors.js";

export class MultiUpstreamProcessManager {
private readonly managers: Record<string, UpstreamProcessManager>;
Expand Down Expand Up @@ -44,7 +45,14 @@ export class MultiUpstreamProcessManager {
}

private manager(name?: string): UpstreamProcessManager {
const selected = name ? this.managers[name] : Object.values(this.managers)[0];
const configured = Object.values(this.managers);
if (!name && configured.length > 1) {
throw new MiftahError(
"UPSTREAM_SELECTION_AMBIGUOUS",
"UPSTREAM_SELECTION_AMBIGUOUS: select an upstream by name when multiple upstreams are configured"
);
}
const selected = name ? this.managers[name] : configured[0];
if (!selected) throw new Error(`No upstream configured${name ? ` named '${name}'` : ""}`);
return selected;
}
Expand Down
1 change: 1 addition & 0 deletions src/utils/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export type MiftahErrorCode =
| "UPSTREAM_INIT_FAILED"
| "UPSTREAM_TOOL_LIST_FAILED"
| "UPSTREAM_CALL_FAILED"
| "UPSTREAM_SELECTION_AMBIGUOUS"
| "ROUTING_AMBIGUOUS"
| "ROUTING_BLOCKED"
| "POLICY_BLOCKED"
Expand Down
Loading