feat: integrate SDK into CLI (#1)

* feat: integrate SDK into CLI

* bump sdk version

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update package.json

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update index.ts

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* update ci

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml

* Update pr-description.yml
This commit is contained in:
Patrick Erichsen 2025-05-02 13:15:45 -07:00 • committed by GitHub
parent 1fefd488c4
commit 597e35b5be
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 1882 additions and 707 deletions

View file

@ -1,4 +1,4 @@
name: Main name: CLI Assistant
version: 0.0.1 version: 0.0.1
schema: v1 schema: v1
@ -6,3 +6,7 @@ models:
- uses: anthropic/claude-3-7-sonnet - uses: anthropic/claude-3-7-sonnet
with: with:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
mcpServers:
- uses: repomix/repomix-mcp
- uses: anthropic/memory-mcp

View file

@ -0,0 +1,36 @@
name: Continue SDK CLI and Hub Context
version: 0.0.1
schema: v1
rules:
- name: Continue SDK CLI and Hub Context
rule: >-
This repository is a CLI for the Continue SDK, which provides programmatic
access to Continue's APIs.
Key components:
- Continue SDK: Experimental package in early development, subject to
breaking changes
- Continue Hub: Registry for custom AI code assistants
- Hub functionality: Manages assistant building blocks (models, rules,
context providers, prompts, docs, etc.)
- Governance: Allows central configuration for organizations
Important libraries:
- WorkOS: Handles authentication flows
- Model Context Protocol (MCP): Manages MCP server interactions
- readline-sync: Provides synchronous CLI user interactions
- Jest: Used for testing framework
All code should follow established patterns for a Node.js CLI tool
interfacing with this experimental SDK.

7
.env.example Normal file
View file

@ -0,0 +1,7 @@
# Continue API settings
# API base URL - defaults to https://api.continue.dev/ if not specified
CONTINUE_API_BASE=http://localhost:3001
# Continue API key
# This is required for authentication with the Continue API
CONTINUE_API_KEY=

209
.github/workflows/pr-description.yml vendored Normal file
View file

@ -0,0 +1,209 @@
name: PR Description Generator
on:
pull_request:
types: [opened, reopened]
issue_comment:
types: [created]
permissions:
contents: read
issues: write
pull-requests: write
actions: write
checks: write
statuses: write
deployments: write
discussions: write
jobs:
generate-description:
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
steps:
- name: Checkout Repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install Continue CLI
run: npm install -g @continuedev/cli
- name: Prepare PR Analysis Files
run: |
# Save changed files list to file
git diff --name-only ${{ github.event.pull_request.base.sha }} ${{ github.event.pull_request.head.sha }} > changed_files.txt
# Create a summarized diff file (limit to 10k lines to avoid size issues)
git diff ${{ github.event.pull_request.base.sha }} ${{ github.event.pull_request.head.sha }} | head -n 1000 > pr_diff.txt
# Create a prompt file that we'll use with continue-cli
cat > prompt.txt << EOL
Analyze this PR and come up with a concise description for the changes.
Do not use any tools, just analyze the provided files and the diff.
Do not write any preamble, just immediately start with the description.
The PR includes these files:
$(cat changed_files.txt)
Here are the changes (first 10k lines):
$(cat pr_diff.txt)
EOL
- name: Analyze PR with Continue
id: analyze
run: |
continue-cli --headless --assistant "starter/nextjs-assistant" "$(cat prompt.txt)" > analysis.txt
echo "analysis_file=analysis.txt" >> $GITHUB_OUTPUT
env:
CONTINUE_API_KEY: con-05c7fd30d8932830c76dca916b866fcb25f65a543b53f11668cfc0c2349322e3
# CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
- name: Add PR Comment
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const fs = require('fs');
const analysisText = fs.readFileSync('analysis.txt', 'utf8');
const comment = `## 🤖 Suggested PR Description
${analysisText}
---
To use this as your PR description, reply with a comment containing just: \`/apply-description\``;
const { data: newComment } = await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: comment
});
update-description:
runs-on: ubuntu-latest
if: |
github.event_name == 'issue_comment' &&
github.event.issue.pull_request &&
github.event.comment.body == '/apply-description'
steps:
- name: React to Comment
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
// Add eyes reaction to show we're processing
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
content: 'eyes'
});
- name: Find Bot Comment
id: find_comment
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number
});
const botComment = comments
.reverse()
.find(comment => comment.body.includes('🤖 Suggested PR Description'));
if (botComment) {
core.setOutput('comment_body', botComment.body);
return true;
}
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
content: '-1' // thumbs down
});
core.setFailed('No bot comment found');
return false;
- name: Update PR Description
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const commentBody = process.env.COMMENT_BODY;
console.log('Processing comment body:', commentBody);
// Extract the description part (between the header and footer)
const descriptionMatch = commentBody.match(/## 🤖 Suggested PR Description\s+([\s\S]*?)\s+---/);
if (descriptionMatch && descriptionMatch[1]) {
const newDescription = descriptionMatch[1].trim();
console.log('Extracted description:', newDescription);
// Update PR description
await github.rest.pulls.update({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number,
body: newDescription
});
// Add a confirmation reply
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `✅ PR description has been updated with the suggested text.`
});
} else {
core.setFailed('Failed to extract description from comment');
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `❌ Error: Could not extract the description from the original comment.`
});
}
env:
COMMENT_BODY: ${{ steps.find_comment.outputs.comment_body }}
- name: Final Reaction
if: success()
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
// Remove eyes reaction
const { data: reactions } = await github.rest.reactions.listForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id
});
const eyesReaction = reactions.find(r => r.content === 'eyes');
if (eyesReaction) {
await github.rest.reactions.deleteForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
reaction_id: eyesReaction.id
});
}
// Add success reaction
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
content: '+1' // thumbs up
});

3
.gitignore vendored
View file

@ -1,3 +1,4 @@
node_modules node_modules
dist dist
.env .env
/*-repomix.xml

115
README.md
View file

@ -1 +1,114 @@
# cli # Continue CLI
A command-line interface for Continue Dev that provides an interactive AI-assisted development experience.
## Features
- 🤖 Interactive AI Assistant Chat
- 🔐 Secure Authentication via WorkOS
- 🛠️ Built-in Development Tools
- ⚡ Real-time Response Streaming
- 🎯 Slash Command Support
- 🤫 Headless Mode for Automation
## Installation
```bash
npm install @continuedev/cli -g
```
## Usage
### Basic Usage
```bash
continue-cli
```
### With Custom Assistant
```bash
continue-cli --assistant-path /path/to/assistant.json
```
### Headless Mode
```bash
continue-cli --headless --prompt "Your command here"
```
## Available Commands
The CLI supports various slash commands during interaction:
- `/help` - Display help information
- `/exit` - Exit the CLI
- Additional commands available during chat sessions
## Development
### Prerequisites
- Node.js (version specified in .nvmrc)
- npm or yarn
### Setup
1. Clone the repository
2. Install dependencies:
```bash
npm install
```
3. Build the project:
```bash
npm run build
```
4. Start in development mode:
```bash
npm start
```
### Testing
Run the test suite:
```bash
npm test
```
## Project Structure
```
src/
├── auth/ # Authentication implementation
├── tools/ # CLI tools and utilities
├── index.ts # Main entry point
├── args.ts # Command line argument parsing
├── client.ts # Client implementation
├── mcp.ts # Model Context Protocol integration
└── ... # Various utility files
```
## Dependencies
- `@continuedev/*` packages for core functionality
- `@workos-inc/node` for authentication
- `openai` for AI capabilities
- Various utility packages (chalk, axios, etc.)
## License
Apache-2.0 - see LICENSE file for details
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## Support
For issues and feature requests, please use the GitHub issue tracker.

1884
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
{ {
"name": "@continuedev/cli", "name": "@continuedev/cli",
"version": "0.0.13", "version": "0.0.15",
"description": "", "description": "",
"main": "dist/index.js", "main": "dist/index.js",
"types": "dist/index.d.ts", "types": "dist/index.d.ts",
@ -11,15 +11,15 @@
"scripts": { "scripts": {
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest", "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
"build": "tsc", "build": "tsc",
"start": "node dist/index.js" "start": "node dist/index.js",
"repomix:sdk": "npx repomix node_modules/@continuedev/sdk --ignore **/api,cli-repomix.xml -o sdk-repomix.xml",
"repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml"
}, },
"author": "Continue Dev, Inc.", "author": "Continue Dev, Inc.",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@continuedev/config-yaml": "^1.0.78",
"@continuedev/hub": "^0.0.6",
"@continuedev/openai-adapters": "^1.0.18", "@continuedev/openai-adapters": "^1.0.18",
"@continuedev/sdk": "^0.0.2", "@continuedev/sdk": "^0.0.9",
"@modelcontextprotocol/sdk": "^1.9.0", "@modelcontextprotocol/sdk": "^1.9.0",
"@workos-inc/node": "^7.45.0", "@workos-inc/node": "^7.45.0",
"axios": "^1.8.4", "axios": "^1.8.4",

View file

@ -114,7 +114,7 @@ function getAuthUrlForTokenPage(useOnboarding: boolean = false): string {
const params = { const params = {
response_type: "code", response_type: "code",
client_id: env.workOsClientId, client_id: env.workOsClientId,
redirect_uri: `${env.appUrl}tokens/${ redirect_uri: `${env.appUrl}/tokens/${
useOnboarding ? "onboarding-" : "" useOnboarding ? "onboarding-" : ""
}callback`, }callback`,
state: uuidv4(), state: uuidv4(),

View file

@ -1,10 +0,0 @@
#!/usr/bin/env node
import { Configuration, DefaultApi } from "@continuedev/sdk";
export const client = new DefaultApi(
new Configuration({
basePath: "https://api.continue.dev",
accessToken: () => "TOKEN", // Replace with your actual token
})
);

36
src/continueSDK.ts Normal file
View file

@ -0,0 +1,36 @@
import { Continue, ContinueClient } from "@continuedev/sdk";
import { env } from "./env.js";
import chalk from "chalk";
/**
* Initialize the Continue SDK with the given parameters
* @param apiKey - API key to use for authentication
* @param assistantSlug - Slug of the assistant to use
* @param organizationId - Optional organization ID
* @returns Promise resolving to the Continue SDK instance
*/
export async function initializeContinueSDK(
apiKey: string | undefined,
assistantSlug: string,
organizationId?: string
): Promise<ContinueClient> {
if (!apiKey) {
console.error(chalk.red("Error: No API key provided for Continue SDK"));
throw new Error("No API key provided for Continue SDK");
}
try {
return await Continue.from({
apiKey,
assistant: assistantSlug,
organizationId,
baseURL: env.apiBase,
});
} catch (error) {
console.error(
chalk.red("Error initializing Continue SDK:"),
error instanceof Error ? error.message : String(error)
);
throw error;
}
}

View file

@ -3,7 +3,7 @@ import dotenv from "dotenv";
dotenv.config(); dotenv.config();
export const env = { export const env = {
apiBase: process.env.CONTINUE_API_BASE ?? "https://api.continue.dev/", apiBase: process.env.CONTINUE_API_BASE ?? "https://api.continue.dev",
workOsClientId: "client_01J0FW6XN8N2XJAECF7NE0Y65J", workOsClientId: "client_01J0FW6XN8N2XJAECF7NE0Y65J",
appUrl: "https://hub.continue.dev/", appUrl: "https://hub.continue.dev",
}; };

View file

@ -1,58 +1,91 @@
#!/usr/bin/env node #!/usr/bin/env node
import { ContinueHubClient } from "@continuedev/hub";
import chalk from "chalk"; import chalk from "chalk";
import { ChatCompletionMessageParam } from "openai/resources.mjs"; import { ChatCompletionMessageParam } from "openai/resources.mjs";
import * as readlineSync from "readline-sync"; import * as readlineSync from "readline-sync";
import { parseArgs } from "./args.js"; import { parseArgs } from "./args.js";
import { ensureAuthenticated } from "./auth/ensureAuth.js"; import { ensureAuthenticated } from "./auth/ensureAuth.js";
import { loadAuthConfig } from "./auth/workos.js"; import { loadAuthConfig } from "./auth/workos.js";
import { env } from "./env.js"; import { initializeContinueSDK } from "./continueSDK.js";
import { introMessage, loadAssistant, loadSystemMessage } from "./intro.js"; import { introMessage } from "./intro.js";
import { MCPService } from "./mcp.js"; import { MCPService } from "./mcp.js";
import { handleSlashCommands } from "./slashCommands.js"; import { handleSlashCommands } from "./slashCommands.js";
import { streamChatResponse } from "./streamChatResponse.js"; import { streamChatResponse } from "./streamChatResponse.js";
import * as fs from "fs";
import { ContinueClient } from "@continuedev/sdk";
// Parse command line arguments // Parse command line arguments
const args = parseArgs(); const args = parseArgs();
// client
// .listAssistants({
// alwaysUseProxy: "true",
// })
// .then((result) => {
// console.log("API result:", result);
// })
// .catch((error) => {
// console.log("API error:", error);
// });
async function chat() { async function chat() {
// Ensure authenticated
const isAuthenticated = await ensureAuthenticated(true); const isAuthenticated = await ensureAuthenticated(true);
if (!isAuthenticated) {
console.error(chalk.red("Authentication failed. Exiting..."));
process.exit(1);
}
const authConfig = loadAuthConfig(); const authConfig = loadAuthConfig();
const hub = new ContinueHubClient({ // Check if the assistant path is a file or a slug
apiKey: authConfig.accessToken, let assistant: ContinueClient["assistant"];
currentUserSlug: "nate", let client: ContinueClient["client"];
orgScopeId: null,
apiBase: env.apiBase,
});
// Load assistant if (fs.existsSync(args.assistantPath)) {
const assistant = await loadAssistant(hub, args.assistantPath); // // If it's a file, load it directly
// console.log(
// chalk.yellow(`Loading assistant from file: ${args.assistantPath}`)
// );
// // We need to extract the assistant slug from the yaml to use with the SDK
// // For now, let's just use a placeholder slug and use the file content for assistant config
// // In a real implementation, we'd need to parse the YAML and extract the slug
// const assistantSlug = "default/assistant";
// try {
// sdkClient = await initializeContinueSDK(
// authConfig.accessToken,
// assistantSlug
// );
// // Since we're using a file, we need to manually set the assistant config
// assistant = JSON.parse(JSON.stringify(sdkClient.assistant.config));
// } catch (error) {
// console.error(
// chalk.red("Error initializing SDK with local file:"),
// error
// );
// throw error;
// }
} else {
// If it's not a file, assume it's a slug
// console.log(
// chalk.yellow(`Loading assistant using slug: ${args.assistantPath}`)
// );
try {
let continueSdk = await initializeContinueSDK(
authConfig.accessToken,
args.assistantPath
);
const mcpService = await MCPService.create(assistant); assistant = continueSdk.assistant;
client = continueSdk.client;
} catch (error) {
console.error(
chalk.red(`Error loading assistant ${args.assistantPath}:`),
error
);
throw error;
}
}
const mcpService = await MCPService.create(assistant!.config);
// Only show intro message if not in headless mode // Only show intro message if not in headless mode
if (!args.isHeadless) { if (!args.isHeadless) {
introMessage(assistant, mcpService); introMessage(assistant!, mcpService);
} }
// Rules // Rules
const chatHistory: ChatCompletionMessageParam[] = []; const chatHistory: ChatCompletionMessageParam[] = [];
const systemMessage = loadSystemMessage(assistant); const systemMessage = assistant!.systemMessage;
if (systemMessage) { if (systemMessage) {
chatHistory.push({ role: "system", content: systemMessage }); chatHistory.push({ role: "system", content: systemMessage });
} }
@ -73,7 +106,7 @@ async function chat() {
isFirstMessage = false; isFirstMessage = false;
// Handle slash commands // Handle slash commands
const commandResult = handleSlashCommands(userInput, assistant); const commandResult = handleSlashCommands(userInput, assistant!.config);
if (commandResult) { if (commandResult) {
if (commandResult.exit) { if (commandResult.exit) {
break; break;
@ -97,13 +130,12 @@ async function chat() {
} }
try { try {
await streamChatResponse(chatHistory, assistant); await streamChatResponse(chatHistory, assistant!, client!);
} catch (e: any) { } catch (e: any) {
console.error(`\n${chalk.red(`Error: ${e.message}`)}`); console.error(`\n${chalk.red(`Error: ${e.message}`)}`);
console.log( console.log(
chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`) chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`)
); );
} finally {
} }
} }
} }

View file

@ -1,51 +1,29 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { ContinueHubClient } from "@continuedev/hub";
import chalk from "chalk"; import chalk from "chalk";
import * as fs from "fs"; import * as fs from "fs";
import { CONTINUE_ASCII_ART } from "./asciiArt.js"; import { CONTINUE_ASCII_ART } from "./asciiArt.js";
import { MCPService } from "./mcp.js"; import { MCPService } from "./mcp.js";
import { getAllTools, getLlmFromAssistant } from "./streamChatResponse.js"; import { getAllTools } from "./streamChatResponse.js";
import { Assistant, type AssistantConfig } from "@continuedev/sdk";
export async function loadAssistant(
hub: ContinueHubClient,
filepathOrSlug: string
): Promise<AssistantUnrolled> {
console.log("Loading assistant ", filepathOrSlug);
if (!fs.existsSync(filepathOrSlug)) {
// Assume it's a slug
console.log("Loading assistant from slug");
return await hub.loadAssistant(filepathOrSlug);
}
const content = fs.readFileSync(filepathOrSlug, "utf-8");
console.log("Loading assistant from file");
const assistant = await hub.loadAssistantFromContent(content);
console.log("loaded: ", assistant.name);
return assistant;
}
export function loadSystemMessage( export function loadSystemMessage(
assistant: AssistantUnrolled assistant: AssistantConfig
): string | undefined { ): string | undefined {
return assistant.rules return assistant.rules
?.filter((rule) => !!rule) ?.filter((rule) => !!rule)
.map((rule) => (typeof rule === "string" ? rule : rule.rule)) .map((rule) => (typeof rule === "string" ? rule : rule?.rule))
.join("\n"); .join("\n");
} }
export function introMessage( export function introMessage(assistant: Assistant, mcpService: MCPService) {
assistant: AssistantUnrolled, const assistantConfig = assistant.config;
mcpService: MCPService
) {
const mcpTools = mcpService.getTools() ?? []; const mcpTools = mcpService.getTools() ?? [];
const mcpPrompts = mcpService.getPrompts() ?? []; const mcpPrompts = mcpService.getPrompts() ?? [];
console.log(chalk.cyan(CONTINUE_ASCII_ART)); console.log(chalk.cyan(CONTINUE_ASCII_ART));
const { model } = getLlmFromAssistant(assistant); console.log(`\n${chalk.bold.blue(`Assistant: ${assistantConfig.name}`)}`);
console.log(`\n${chalk.bold.blue(`Assistant: ${assistant.name}`)}`); console.log(`${chalk.blue(`Model: ${assistant.getModel()}`)}\n`);
console.log(`${chalk.blue(`Model: ${model}`)}\n`);
console.log(chalk.yellow("Available tools:")); console.log(chalk.yellow("Available tools:"));
getAllTools().forEach((tool) => { getAllTools().forEach((tool) => {
@ -66,22 +44,24 @@ export function introMessage(
console.log("- /login: Authenticate with your account"); console.log("- /login: Authenticate with your account");
console.log("- /logout: Sign out of your current session"); console.log("- /logout: Sign out of your current session");
console.log("- /whoami: Check who you're currently logged in as"); console.log("- /whoami: Check who you're currently logged in as");
for (const prompt of assistant.prompts ?? []) { for (const prompt of assistantConfig.prompts ?? []) {
console.log(`- /${prompt.name}: ${prompt.description}`); console.log(`- /${prompt?.name}: ${prompt?.description}`);
} }
for (const prompt of mcpPrompts) { for (const prompt of mcpPrompts) {
console.log(`- /${prompt.name}: ${prompt.description}`); console.log(`- /${prompt.name}: ${prompt.description}`);
} }
console.log(""); console.log("");
if (assistant.rules?.length) { if (assistantConfig.rules?.length) {
console.log(chalk.yellow("\nAssistant rules: " + assistant.rules.length)); console.log(
chalk.yellow("\nAssistant rules: " + assistantConfig.rules.length)
);
} }
if (assistant.mcpServers?.length) { if (assistantConfig.mcpServers?.length) {
console.log(chalk.yellow("\nMCP Servers:")); console.log(chalk.yellow("\nMCP Servers:"));
assistant.mcpServers.forEach((server) => { assistantConfig.mcpServers.forEach((server: any) => {
console.log(`- ${chalk.cyan(server.name)}`); console.log(`- ${chalk.cyan(server?.name)}`);
}); });
} }
console.log(""); console.log("");

View file

@ -1,4 +1,4 @@
import { AssistantUnrolled } from "@continuedev/config-yaml"; import { type AssistantConfig } from "@continuedev/sdk";
import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
@ -6,11 +6,11 @@ export class MCPService {
private readonly connections: MCPConnection[] = []; private readonly connections: MCPConnection[] = [];
private static instance: MCPService | null = null; private static instance: MCPService | null = null;
private constructor(private readonly assistant: AssistantUnrolled) { private constructor(private readonly assistant: AssistantConfig) {
this.assistant = assistant; this.assistant = assistant;
} }
public static async create(assistant: AssistantUnrolled) { public static async create(assistant: AssistantConfig) {
// If instance already exists, return it // If instance already exists, return it
if (MCPService.instance) { if (MCPService.instance) {
return MCPService.instance; return MCPService.instance;
@ -21,7 +21,7 @@ export class MCPService {
if (assistant.mcpServers?.length) { if (assistant.mcpServers?.length) {
const connectionPromises = assistant.mcpServers.map((server) => const connectionPromises = assistant.mcpServers.map((server) =>
MCPConnection.create(server), MCPConnection.create(server)
); );
const connections = await Promise.all(connectionPromises); const connections = await Promise.all(connectionPromises);
service.connections.push(...connections); service.connections.push(...connections);
@ -65,24 +65,29 @@ export class MCPConnection {
private constructor(public readonly client: Client) {} private constructor(public readonly client: Client) {}
public static async create( public static async create(
config: NonNullable<AssistantUnrolled["mcpServers"]>[number], config: NonNullable<AssistantConfig["mcpServers"]>[number]
) { ) {
const client = new Client( const client = new Client(
{ {
name: "continue-cli-client", name: "continue-cli-client",
version: "1.0.0", version: "1.0.0",
}, },
{ capabilities: {} }, { capabilities: {} }
); );
// Construct transport // Construct transport
const env: Record<string, string> = config.env || {}; const env: Record<string, string> = config?.env || {};
if (process.env.PATH !== undefined) { if (process.env.PATH !== undefined) {
env.PATH = process.env.PATH; env.PATH = process.env.PATH;
} }
if (!config?.command) {
throw new Error("MCP server command is not specified");
}
const transport = new StdioClientTransport({ const transport = new StdioClientTransport({
command: config.command, command: config.command,
args: config.args, args: config?.args,
env, env,
}); });

View file

@ -1,4 +1,3 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import chalk from "chalk"; import chalk from "chalk";
import { import {
isAuthenticated, isAuthenticated,
@ -6,10 +5,11 @@ import {
login, login,
logout, logout,
} from "./auth/workos.js"; } from "./auth/workos.js";
import { type AssistantConfig } from "@continuedev/sdk";
export function handleSlashCommands( export function handleSlashCommands(
input: string, input: string,
assistant: AssistantUnrolled, assistant: AssistantConfig
): { ): {
output?: string; output?: string;
exit?: boolean; exit?: boolean;
@ -28,13 +28,16 @@ export function handleSlashCommands(
"/whoami - Check who you're currently logged in as", "/whoami - Check who you're currently logged in as",
"/models - List available AI models", "/models - List available AI models",
...(assistant.prompts?.map( ...(assistant.prompts?.map(
(prompt) => `/${prompt.name} - ${prompt.description}`, (prompt) => `/${prompt?.name} - ${prompt?.description}`
) ?? []), ) ?? []),
].join("\n"); ].join("\n");
return { output: helpMessage }; return { output: helpMessage };
case "models": case "models":
return { return {
output: `Available models:\n• ${assistant.models?.map((model) => model.name)?.join("\n• ") || "None"}`, output: `Available models:\n• ${
assistant.models?.map((model) => model?.name)?.join("\n• ") ||
"None"
}`,
}; };
case "exit": case "exit":
return { exit: true, output: "Goodbye!" }; return { exit: true, output: "Goodbye!" };
@ -42,9 +45,7 @@ export function handleSlashCommands(
login() login()
.then((config) => { .then((config) => {
console.log( console.log(
chalk.green( chalk.green(`\nLogged in as ${config.userEmail || config.userId}`)
`\nLogged in as ${config.userEmail || config.userId}`,
),
); );
}) })
.catch((error) => { .catch((error) => {
@ -78,7 +79,7 @@ export function handleSlashCommands(
default: default:
const assistantPrompt = assistant.prompts?.find( const assistantPrompt = assistant.prompts?.find(
(prompt) => prompt.name === command, (prompt) => prompt?.name === command
); );
if (assistantPrompt) { if (assistantPrompt) {
const newInput = assistantPrompt.prompt + args.join(" "); const newInput = assistantPrompt.prompt + args.join(" ");

View file

@ -1,9 +1,6 @@
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { constructLlmApi } from "@continuedev/openai-adapters";
import chalk from "chalk"; import chalk from "chalk";
import * as dotenv from "dotenv"; import * as dotenv from "dotenv";
import { import type {
ChatCompletionChunk,
ChatCompletionMessageParam, ChatCompletionMessageParam,
ChatCompletionMessageToolCall, ChatCompletionMessageToolCall,
ChatCompletionTool, ChatCompletionTool,
@ -11,30 +8,10 @@ import {
import { MCPService } from "./mcp.js"; import { MCPService } from "./mcp.js";
import { executeToolCall } from "./tools.js"; import { executeToolCall } from "./tools.js";
import { BUILTIN_TOOLS } from "./tools/index.js"; import { BUILTIN_TOOLS } from "./tools/index.js";
import { ContinueClient } from "@continuedev/sdk";
dotenv.config(); dotenv.config();
export function getLlmFromAssistant(assistant: AssistantUnrolled) {
const chatModel = assistant.models?.filter((model) =>
model?.roles?.includes("chat"),
)?.[0];
if (!chatModel) {
console.error(chalk.red("Error: No chat model found in the assistant."));
process.exit(1);
}
const llm = constructLlmApi({
provider: chatModel.provider as any,
apiKey: chatModel.apiKey,
apiBase: chatModel.apiBase,
});
if (!llm) {
console.error(chalk.red("Error: Failed to construct LLM API."));
process.exit(1);
}
return { llm, model: chatModel.model };
}
export function getAllTools() { export function getAllTools() {
const allTools: ChatCompletionTool[] = BUILTIN_TOOLS.map((tool) => ({ const allTools: ChatCompletionTool[] = BUILTIN_TOOLS.map((tool) => ({
type: "function" as const, type: "function" as const,
@ -47,7 +24,7 @@ export function getAllTools() {
Object.entries(tool.parameters).map(([key, param]) => [ Object.entries(tool.parameters).map(([key, param]) => [
key, key,
{ type: param.type, description: param.description }, { type: param.type, description: param.description },
]), ])
), ),
required: Object.entries(tool.parameters) required: Object.entries(tool.parameters)
.filter(([_, param]) => param.required) .filter(([_, param]) => param.required)
@ -65,7 +42,7 @@ export function getAllTools() {
description: tool.description, description: tool.description,
parameters: tool.inputSchema, parameters: tool.inputSchema,
}, },
})), }))
); );
return allTools; return allTools;
@ -76,10 +53,9 @@ type TODO = any;
// Define a function to handle streaming responses with tool calling // Define a function to handle streaming responses with tool calling
export async function streamChatResponse( export async function streamChatResponse(
chatHistory: ChatCompletionMessageParam[], chatHistory: ChatCompletionMessageParam[],
assistant: AssistantUnrolled, assistant: ContinueClient["assistant"],
client: ContinueClient["client"]
) { ) {
const { llm, model } = getLlmFromAssistant(assistant);
// Prepare tools for the API call // Prepare tools for the API call
const toolsForRequest = getAllTools(); const toolsForRequest = getAllTools();
@ -88,21 +64,19 @@ export async function streamChatResponse(
let shouldContinueConversation = true; let shouldContinueConversation = true;
while (shouldContinueConversation) { while (shouldContinueConversation) {
let stream: AsyncGenerator<ChatCompletionChunk, any, any>; let stream;
try { try {
stream = llm.chatCompletionStream( stream = await client.chat.completions.create({
{ model: assistant.getModel(),
model, messages: chatHistory,
messages: chatHistory, stream: true,
stream: true, tools: toolsForRequest,
tools: toolsForRequest, });
},
new AbortController().signal,
);
} catch (error: any) { } catch (error: any) {
console.error( console.error(
chalk.red("Error in streamChatResponse:"), chalk.red("Error in streamChatResponse:"),
chalk.red(error.message), chalk.red(error.message)
); );
process.exit(1); process.exit(1);
} }
@ -138,13 +112,15 @@ export async function streamChatResponse(
// Add function name if present // Add function name if present
if (toolCallDelta.function?.name) { if (toolCallDelta.function?.name) {
const toolCall = currentToolCalls.find( const toolCall = currentToolCalls.find(
(tc) => tc.id === currentToolCallId, (tc) => tc.id === currentToolCallId
); );
if (toolCall) { if (toolCall) {
if (!toolCall.name) { if (!toolCall.name) {
toolCall.name = toolCallDelta.function.name; toolCall.name = toolCallDelta.function.name;
process.stdout.write( process.stdout.write(
`\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold(toolCall.name)}${chalk.yellow("]")}`, `\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold(
toolCall.name
)}${chalk.yellow("]")}`
); );
} }
} }
@ -153,7 +129,7 @@ export async function streamChatResponse(
// Collect function arguments // Collect function arguments
if (toolCallDelta.function?.arguments) { if (toolCallDelta.function?.arguments) {
const toolCall = currentToolCalls.find( const toolCall = currentToolCalls.find(
(tc) => tc.id === currentToolCallId, (tc) => tc.id === currentToolCallId
); );
if (toolCall) { if (toolCall) {
// Accumulate arguments as string to later parse as JSON // Accumulate arguments as string to later parse as JSON
@ -184,7 +160,7 @@ export async function streamChatResponse(
name: tc.name, name: tc.name,
arguments: JSON.stringify(tc.arguments), arguments: JSON.stringify(tc.arguments),
}, },
}), })
); );
chatHistory.push({ chatHistory.push({
role: "assistant", role: "assistant",
@ -212,14 +188,18 @@ export async function streamChatResponse(
console.log(chalk.green(toolResult) + "\n"); console.log(chalk.green(toolResult) + "\n");
} catch (error) { } catch (error) {
const errorMessage = `Error executing tool ${toolCall.name}: ${error instanceof Error ? error.message : String(error)}`; const errorMessage = `Error executing tool ${toolCall.name}: ${
error instanceof Error ? error.message : String(error)
}`;
chatHistory.push({ chatHistory.push({
role: "tool", role: "tool",
tool_call_id: toolCall.id, tool_call_id: toolCall.id,
content: errorMessage, content: errorMessage,
}); });
console.log( console.log(
`${chalk.red("[Tool error:")} ${chalk.red(errorMessage)}${chalk.red(")")}`, `${chalk.red("[Tool error:")} ${chalk.red(errorMessage)}${chalk.red(
")"
)}`
); );
} }
} }

View file

@ -2,6 +2,7 @@
"compilerOptions": { "compilerOptions": {
"target": "ESNext", "target": "ESNext",
"module": "NodeNext", "module": "NodeNext",
"moduleResolution": "NodeNext",
"useDefineForClassFields": true, "useDefineForClassFields": true,
"lib": ["DOM", "ESNext"], "lib": ["DOM", "ESNext"],
"allowJs": true, "allowJs": true,
@ -10,14 +11,14 @@
"allowSyntheticDefaultImports": true, "allowSyntheticDefaultImports": true,
"strict": true, "strict": true,
"forceConsistentCasingInFileNames": true, "forceConsistentCasingInFileNames": true,
"moduleResolution": "NodeNext",
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": false, "isolatedModules": false,
"noEmitOnError": false, "noEmitOnError": false,
"types": ["node", "jest"], "types": ["node", "jest"],
"outDir": "dist", "outDir": "dist",
"declaration": true "declaration": true,
// "sourceMap": true "sourceMap": true,
"inlineSources": true
}, },
"include": ["src/**/*"] "include": ["src/**/*"]
} }