# How to Configure and Manage MCP Servers Using the Source-Manager in Craft Agents

> Learn to configure and manage MCP servers with Craft Agents Source-Manager. This tool centralizes server lifecycle, formats LLM context, and automates error remediation.

- Repository: [Craft Ai Agents/craft-agents-oss](https://github.com/craft-ai-agents/craft-agents-oss)
- Tags: how-to-guide
- Published: 2026-07-06

---

**The `SourceManager` class in craft-ai-agents/craft-agents-oss provides a centralized lifecycle manager for MCP servers, tracking active states, formatting XML context blocks for LLMs, and handling automatic remediation through structured error detection.**

Craft Agents orchestrates external services through **MCP (Message-Control-Protocol) servers**, requiring a robust mechanism to track their dynamic state according to the craft-ai-agents/craft-agents-oss source code. The `SourceManager` class, located in [`packages/shared/src/agent/core/source-manager.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/agent/core/source-manager.ts), serves as the single source of truth to configure and manage MCP servers, injecting structured `<sources>` blocks into LLM contexts while maintaining synchronization between UI expectations and actual process states.

## Core Responsibilities of the SourceManager

The `SourceManager` centralizes five critical functions for MCP server administration.

### Tracking Active versus Intended States

The `updateActiveState(mcpServerNames, apiServerNames, intendedSlugs?)` method maintains two distinct lists: `activeSlugs` representing actually running MCP processes, and `intendedSlugs` reflecting the UI's displayed state. This separation allows the interface to show a server as active even when tool initialization failed, while the manager retains accurate process awareness.

### Catalog Management

Calling `setAllSources(sources)` populates the `allSources` array with every discovered source definition from [`sources.json`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/sources.json) or UI state. This creates visibility into all configured MCP servers regardless of their current runtime status.

### LLM Context Formatting

The `formatSourceState()` method constructs a machine-readable `<sources>` XML block that categorizes servers as Active, Inactive, New, or Problem sources. When authentication is required, it appends a `<source_issue>` element containing prescriptive remediation steps, automatically reminding the LLM to consult [`guide.md`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/guide.md) before tool invocation.

### Inactive Source Detection

When tool calls fail with patterns like "No such tool …", the `detectInactiveSourceToolError(toolName, errorMessage)` method identifies missing MCP servers by parsing the `mcp__{slug}__{tool}` naming convention. This enables automatic server activation and request retry without manual intervention.

### Authentication Management

The `getAuthToolName(source)` method returns the appropriate authentication trigger tool for OAuth or bearer token flows, allowing the LLM to initiate re-authentication sequences programmatically.

## MCP Server Lifecycle Integration

MCP servers flow through a five-stage integration pipeline within the `SourceManager`.

### 1. Source Discovery

During agent startup, the source loader reads [`sources.json`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/sources.json) and constructs `LoadedSource` objects containing `type: 'mcp'` configurations, unique slugs, transport settings, and optional guide metadata.

### 2. Registration

The agent registers all discovered definitions via `sourceManager.setAllSources(loadedSources)`, establishing the complete catalog of available MCP integrations.

### 3. Activation Tracking

When MCP processes launch (typically via [`scripts/install-server.sh`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/scripts/install-server.sh)), the system calls `updateActiveState()` with running server names. The manager differentiates between actually running processes (`activeSlugs`) and UI-indicated states (`intendedSlugs`), ensuring consistent messaging even during partial failures.

### 4. Context Injection

Every LLM prompt includes the XML snapshot generated by `formatSourceState()`:

```xml
<sources>
Active: mcp-github, mcp-slack (no tools)
Inactive: mcp-jira (needs auth)
New:
- mcp-salesforce: Salesforce CRM
</sources>

```

This structured format enables the LLM to reason about tool availability and authentication requirements dynamically.

### 5. Error Recovery

Failed tool invocations trigger `detectInactiveSourceToolError()`, which extracts the missing source slug from error messages. The session manager uses this signal to auto-start the required MCP server before retrying the original request.

## Practical Configuration Examples

### Initializing the Source Manager

```typescript
import { SourceManager } from '@craft-agents/shared/agent/core';
import type { LoadedSource } from '@craft-agents/shared/sources/types';

// Create manager with optional debug logging
const sourceManager = new SourceManager({
  onDebug: (msg) => console.debug('[SourceManager]', msg),
});

// Load definitions from configuration
const allSources: LoadedSource[] = await loadSources();
sourceManager.setAllSources(allSources);

// Register running MCP servers
sourceManager.updateActiveState(
  ['mcp-github', 'mcp-slack'], // Actually running
  [],                         // API servers (none here)
  ['mcp-github', 'mcp-slack', 'mcp-jira'] // UI intended list
);

```

### Generating LLM Context

```typescript
const sourcesXml = sourceManager.formatSourceState();
const prompt = `You are a helpful assistant.\n${sourcesXml}\nUser request: …`;

```

### Handling Tool Failures

```typescript
function handleToolError(toolName: string, errMsg: string) {
  const maybe = sourceManager.detectInactiveSourceToolError(toolName, errMsg);
  if (maybe) {
    // Auto-start the missing MCP server
    startMcpServer(maybe.sourceSlug);
    // Retry original tool call after server initialization
  }
}

```

### Managing Authentication

```typescript
const source = sourceManager.getAllSources().find(
  (s) => s.config.slug === 'mcp-jira' && s.config.connectionStatus === 'needs_auth'
);

if (source) {
  const authTool = sourceManager.getAuthToolName(source);
  console.log(`Execute authentication: ${authTool}`);
}

```

### Marking Sources as Seen

To prevent repeated guide prompts within a session:

```typescript
sourceManager.markSourceSeen('mcp-github');

```

## Key Implementation Files

The MCP server management system spans several critical files in the craft-ai-agents/craft-agents-oss repository:

- [`packages/shared/src/agent/core/source-manager.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/agent/core/source-manager.ts) – Core `SourceManager` class implementing `updateActiveState`, `formatSourceState`, and error detection logic.
- [`packages/shared/src/agent/core/__tests__/source-manager.test.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/agent/core/__tests__/source-manager.test.ts) – Test suite demonstrating active/inactive state handling and XML formatting.
- [`packages/shared/src/sources/types.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/sources/types.ts) – Type definitions for `LoadedSource`, source configurations, and MCP-specific fields.
- [`packages/shared/src/sources/credential-manager.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/sources/credential-manager.ts) – Authentication state evaluation via `sourceNeedsAuthentication`.
- [`scripts/install-server.sh`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/scripts/install-server.sh) – Reference implementation for MCP server launch scripts.
- [`docs/cli.md`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/docs/cli.md) – CLI integration documentation for the source management workflow.

## Summary

- The `SourceManager` class in [`packages/shared/src/agent/core/source-manager.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/packages/shared/src/agent/core/source-manager.ts) provides centralized MCP server lifecycle management.
- **Active versus intended tracking** allows accurate backend state management while maintaining UI consistency through `updateActiveState()`.
- **XML context generation** via `formatSourceState()` provides LLMs with structured visibility into server availability and authentication requirements.
- **Automatic error recovery** through `detectInactiveSourceToolError()` enables self-healing workflows when MCP servers are temporarily unavailable.
- **Authentication helpers** streamline OAuth and bearer token flows without manual configuration steps.

## Frequently Asked Questions

### How does the SourceManager differentiate between running and configured MCP servers?

The manager maintains two distinct arrays: `activeSlugs` tracks actually running MCP processes passed to `updateActiveState()`, while `intendedSlugs` represents servers the UI expects to be active. This distinction allows the system to handle partial failures where a server process exists but tools failed to initialize, ensuring accurate state representation for both backend logic and user interface displays.

### What format does the SourceManager use to communicate MCP status to the LLM?

The `formatSourceState()` method generates a structured XML block containing `<sources>` elements categorized as Active, Inactive, New, or Problem sources. When authentication is required, the method appends a `<source_issue>` element with specific remediation instructions, enabling the LLM to understand not just which tools are available, but which require additional setup steps before use.

### Can the SourceManager automatically recover from MCP server failures?

Yes. The `detectInactiveSourceToolError()` method parses tool names following the `mcp__{slug}__{tool}` convention to identify when a request targets an inactive server. When detected, the method returns the missing source slug, allowing the session manager to automatically launch the required MCP process via [`scripts/install-server.sh`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/scripts/install-server.sh) and retry the failed tool invocation without user intervention.

### How does authentication configuration work for MCP servers requiring OAuth?

The `getAuthToolName()` method determines the correct authentication trigger tool for each source based on its configuration type. For OAuth-enabled MCP servers, this returns the appropriate `source_oauth_trigger` tool name, which the LLM can then invoke to initiate the authentication flow. The [`credential-manager.ts`](https://github.com/craft-ai-agents/craft-agents-oss/blob/main/credential-manager.ts) module handles the underlying validation of authentication states through the `sourceNeedsAuthentication` helper.