Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
7 changes: 7 additions & 0 deletions packages/extension-agent/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ ChatLuna Agent 框架,提供 MCP、Skills、Scheduler、Tool 和 Sub-Agent 支
## 功能

- **MCP**: Model Context Protocol 支持
- **MCP 目录懒加载**: 通过稳定的 `search_mcp_tools` 和
`invoke_mcp_tool` 按需检索契约并调用真实工具。搜索先返回精简摘要,
选定工具后再单独加载完整 Schema。
- **Skills**: 技能管理(规划中)
- **Scheduler**: 任务调度(规划中)
- **Tool**: 工具管理(规划中)
Expand All @@ -23,6 +26,10 @@ ctx.chatluna_agent.mcp.listTools()

配置文件位于 `data/chatluna/agents/config.json`。

插件全局配置 `mcpToolMode` 默认为 `eager`(暴露全部 MCP 工具)。
设为 `catalog` 时,模型只会收到固定的搜索和调用网关工具,
真实 MCP 工具的契约在需要时才加载。

## License

AGPL-3.0
27 changes: 23 additions & 4 deletions packages/extension-agent/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/** @module extension-agent */

import { Context, Logger, Schema } from 'koishi'
import { ClientConfig } from 'koishi-plugin-chatluna/llm-core/platform/config'
import { createLogger } from 'koishi-plugin-chatluna/utils/logger'
import { ChatLunaPlugin } from 'koishi-plugin-chatluna/services/chat'
import { ChatLunaAgentService } from './service'
Expand All @@ -15,12 +16,17 @@ import { cleanupExpiredOutputs } from './computer/backends/local/output'
export * from './types'

export let logger: Logger
export let plugin: ChatLunaPlugin
export let plugin: ChatLunaPlugin<ClientConfig, Config>

export async function apply(ctx: Context, config: Config) {
logger = createLogger(ctx, 'chatluna-agent')

plugin = new ChatLunaPlugin(ctx, config, 'agent', false)
plugin = new ChatLunaPlugin<ClientConfig, Config>(
ctx,
config,
'agent',
false
)
await migrateAgentData(ctx)

ctx.plugin(ChatLunaAgentService, {
Expand All @@ -43,9 +49,22 @@ export async function apply(ctx: Context, config: Config) {
ctx.plugin(taskCommands)
}

export const Config: Schema<Config> = Schema.intersect([ChatLunaPlugin.Config])
export const Config: Schema<Config> = Schema.intersect([
ChatLunaPlugin.Config,
Schema.object({
mcpToolMode: Schema.union([
Schema.const('eager'),
Schema.const('catalog')
]).default('eager')
})
]).i18n({
'zh-CN': require('./locales/zh-CN.schema.yml'),
'en-US': require('./locales/en-US.schema.yml')
}) as Schema<Config>

export interface Config extends ChatLunaPlugin.Config {}
export interface Config extends ChatLunaPlugin.Config {
mcpToolMode: 'eager' | 'catalog'
}

export const inject = {
required: ['chatluna', 'console'],
Expand Down
8 changes: 8 additions & 0 deletions packages/extension-agent/src/locales/en-US.schema.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1,10 @@
name: ChatLuna Agent Framework
description: Provides MCP, Skills, Scheduler, Tool and Sub-Agent support
$inner:
- {}
- $desc: MCP tool loading
mcpToolMode:
$desc: Controls how MCP tools are disclosed to the model.
$inner:
- Eager mode. Send every enabled MCP tool's complete schema to the model.
- Catalog lazy-loading mode. Keep only stable search and invoke gateway tools in context, and retrieve real tool contracts on demand.
8 changes: 8 additions & 0 deletions packages/extension-agent/src/locales/zh-CN.schema.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1,10 @@
name: ChatLuna Agent 框架
description: 提供 MCP、Skills、Scheduler、Tool 和 Sub-Agent 支持
$inner:
- {}
- $desc: MCP 工具加载
mcpToolMode:
$desc: MCP 工具向模型的披露方式。
$inner:
- 全量模式。将所有已启用 MCP 工具的完整 Schema 发送给模型。
- 目录懒加载模式。模型只常驻搜索和调用两个网关工具,按需检索真实工具契约。
140 changes: 140 additions & 0 deletions packages/extension-agent/src/mcp/catalog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/** @module mcp/catalog */

import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'
import { JsonSchemaType } from '@modelcontextprotocol/sdk/validation'

export type McpCatalogTool = {
name: string
summary: string
parameters: string
keywords: string[]
inputSchema: Record<string, unknown>
}

export type McpCatalogSourceTool = {
name: string
title?: string
description?: string
inputSchema: Record<string, unknown>
}

export function createMcpCatalogTool(
tool: McpCatalogSourceTool
): McpCatalogTool {
return {
name: tool.name,
summary: (tool.description || `MCP tool ${tool.name}`)
.trim()
.slice(0, 200),
parameters: formatParameters(tool.inputSchema),
keywords: Array.from(
new Set(
`${tool.name} ${tool.title ?? ''} ${tool.description ?? ''}`
.toLowerCase()
.split(/[^\p{L}\p{N}_-]+/u)
.filter(Boolean)
)
).slice(0, 12),
inputSchema: tool.inputSchema
}
}

export function scoreMcpCatalogTool(
query: string,
server: string,
tool: McpCatalogTool
) {
const value = query.trim().toLowerCase()
const text =
`${server} ${tool.name} ${tool.summary} ${tool.parameters} ${tool.keywords.join(' ')}`.toLowerCase()
let score = text.includes(value) ? 100 : 0

for (const word of value
.split(/[^\p{L}\p{N}_-]+/u)
.filter((item) => item.length > 1)) {
if (text.includes(word)) score += 10
}

const compact = value.replace(/\s+/g, '')
for (let i = 0; i < compact.length - 1; i++) {
if (text.includes(compact.slice(i, i + 2))) score++
}

if (`${server}/${tool.name}`.toLowerCase() === value) score += 200
return score
}

export function createMcpCatalogSummaryResult(
server: string,
tool: McpCatalogTool
) {
return {
server,
name: tool.name,
summary: tool.summary,
parameters: tool.parameters
}
}

export function createMcpCatalogSchemaResult(
server: string,
tool: McpCatalogTool
) {
return {
...createMcpCatalogSummaryResult(server, tool),
inputSchema: tool.inputSchema
}
}

export function validateMcpArguments(
validator: AjvJsonSchemaValidator,
schema: Record<string, unknown>,
args: Record<string, unknown>
): McpArgumentValidation {
try {
const result = validator.getValidator<Record<string, unknown>>(
schema as JsonSchemaType
)(args)
if (!result.valid) {
return {
valid: false,
error: 'validation_error',
message: result.errorMessage
}
}
return { valid: true, data: result.data }
} catch (error) {
return {
valid: false,
error: 'schema_error',
message: error instanceof Error ? error.message : String(error)
}
}
}

export type McpArgumentValidation =
| { valid: true; data: Record<string, unknown> }
| {
valid: false
error: 'validation_error' | 'schema_error'
message: string
}

function formatParameters(schema: Record<string, unknown>) {
const source = schema as {
properties?: Record<string, { type?: string; description?: string }>
required?: string[]
}
const required = new Set(source.required ?? [])
const properties = Object.entries(source.properties ?? {})
if (properties.length === 0) return 'No parameters'

return properties
.map(([name, info]) => {
const type = info.type ?? 'value'
const description = info.description ? ` - ${info.description}` : ''
return `${name}${required.has(name) ? ' (required)' : ''}: ${type}${description}`
})
.join('; ')
.slice(0, 200)
}
8 changes: 6 additions & 2 deletions packages/extension-agent/src/service/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import { mkdir, rm, stat, writeFile } from 'fs/promises'
import os from 'node:os'
import { dirname, join, resolve } from 'path'
import { Context, Service } from 'koishi'
import { ClientConfig } from 'koishi-plugin-chatluna/llm-core/platform/config'
import { ChatLunaPlugin } from 'koishi-plugin-chatluna/services/chat'
import { logger } from '..'
import { type Config, logger } from '..'
import { truncateOutput } from '../computer/backends/types'
import type { ComputerSessionApi } from '../computer/types'
import { createSubAgentItemConfig } from '../config/defaults'
Expand Down Expand Up @@ -60,7 +61,10 @@ export class ChatLunaAgentService extends Service {

constructor(
public ctx: Context,
public args: { config: AgentConfig; plugin: ChatLunaPlugin }
public args: {
config: AgentConfig
plugin: ChatLunaPlugin<ClientConfig, Config>
}
) {
super(ctx, 'chatluna_agent')

Expand Down
Loading
Loading