LLMling について
LLMling は、MCP サーバーと AI エージェントを YAML で宣言的に定義して LLM アプリケーションを構築するフレームワークです。コードよりも設定ファイルで構成したい開発者を対象とし、pydantic-AI をベースに Python 3.12 以上を必要とします。
主な機能
- 01YAML による宣言的な設定
- 02リソース、プロンプト、ツールの3種類のコンポーネント
- 03ファイル監視とリソース処理パイプライン
- 04関数およびクラスによるツール定義
- 05エントリーポイントで登録するツールセット
活用シーン
- 01YAML ファイルからカスタム MCP サーバーを素早く構築
- 02LLMling サーバーを Zed や Claude Desktop に接続
- 03pydantic-AI で定義済みツールを呼び出すエージェントを作成
MCP 対応
LLMling は YAML 設定から MCP サーバーを起動し、リソース、プロンプト、ツールを Zed や Claude Desktop などの MCP クライアントに公開します。
設定
ローカルサーバーの設定はどのクライアントでも共通です。コピーしてクライアントの MCP 設定ファイルに貼り付けてください。
ツール
ローカルサーバーのツールはマシン上で起動して初めて取得できます。メンテナーはまだツール一覧を提供していません。
詳細
LLMling
リソース管理、プロンプトテンプレート、ツールの実行に重点を置いた、宣言的なLLMアプリケーション開発のためのフレームワークです。
このパッケージは、2つの利用者向けのバックエンドを提供します:MCP サーバーとpydantic-AIベースのエージェント
コアコンセプト
LLMLingは、LLMアプリケーション向けのYAMLベースの設定システムを提供します。 YAMLファイルで定義したコンテンツを提供する、カスタムMPCサーバーを設定できます。
- 静的な宣言:コードを記述せずに、LLMの環境をYAMLで定義します
- MCPプロトコル:標準化されたLLMとの対話のため、Machine Chat Protocol(MCP)を基盤に構築されています
- コンポーネントの種類:
- リソース:コンテンツプロバイダー(ファイル、テキスト、CLI出力など)
- プロンプト:引数を持つメッセージテンプレート
- ツール:LLMから呼び出し可能なPython関数
YAML設定により、LLMに以下を提供する完全な環境が構築されます:
-
リソースを介したコンテンツへのアクセス
-
一貫したやり取りのための構造化されたプロンプト
-
機能を拡張するためのツール
-
最新のPythonで一から記述(最低3.12が必要)
-
100%型付け済み
-
pydantic(およびpydantic-ai)ベース
システム全体の概要:
graph TB
subgraph LLMling[LLMling Core Package]
RT[RuntimeConfig]
subgraph Core_Components[Core Components]
Resources[Resource Management<br/>- Load files/URLs<br/>- Process content<br/>- Watch changes]
Tools[Tool System<br/>- Execute functions<br/>- Register new tools<br/>- OpenAPI integration]
Prompts[Prompt System<br/>- Static/Dynamic prompts<br/>- Template rendering<br/>- Completion support]
end
CLI[Core CLI<br/>- config add/remove/list<br/>- resource list/load<br/>- tool list/execute<br/>- prompt list/render]
Core_Components -->|YAML configuration| RT
RT -->|All components| CLI
CLI -->|modify| Core_Components
end
subgraph Direct_Access[mcp-server-llmling<br/>Direct Component Access]
MCP[HTTP/SSE Server<br/>- Start/Stop server]
MCP_CLI[Server CLI<br/>- Start/Stop server]
Injection[Injection Server<br/>- Inject components<br/>during runtime]
end
subgraph Function_Access[llmling-agent<br/>Access via Function Calling]
LLM[LLM Integration<br/>- Function calling<br/>- Resource access<br/>- Tool execution<br/>- Structured output]
Agent_CLI[Agent CLI<br/>- One-shot execution<br/>- Batch processing]
Agent_Web[Agent Web UI<br/>- Interactive chat]
end
RT -->|All components| MCP
RT -->|Resources & Tools<br/>via function calling| LLM
MCP_CLI --> CLI
Agent_CLI --> CLI
classDef core fill:#e1f5fe,stroke:#01579b
classDef comp fill:#e3f2fd,stroke:#1565c0
classDef cli fill:#fff3e0,stroke:#e65100
classDef mcp fill:#f3e5f5,stroke:#4a148c
classDef agent fill:#e8f5e9,stroke:#1b5e20
classDef access fill:#e8eaf6,stroke:#666
classDef serverBox fill:#7986cb,stroke:#3949ab
classDef agentBox fill:#81c784,stroke:#2e7d32
class RT core
class Resources,Tools,Prompts comp
class CLI,MCP_CLI,Agent_CLI cli
class MCP,Injection mcp
class LLM,Agent_Web agent
class Direct_Access serverBox
class Function_Access agentBox
使用方法
1. CLIの使用方法
基本的な設定ファイルを作成します:
# Create a new config file with basic settings
llmling config init my_config.yml
# Add it to your stored configs
llmling config add myconfig my_config.yml
llmling config set myconfig # Make it active
基本的なCLIコマンド:
# List available resources
llmling resource list
# Load a resource
llmling resource load python_files
# Execute a tool
llmling tool call open_url url=https://github.com
# Show a prompt
llmling prompt show greet
# Many more commands. The CLI will get extended when installing
# llmling-agent and mcp-server-llmling
2. エージェントの使用方法(pydantic-AI を使用)
設定ファイル(config.yml)を作成します:
tools:
open_url:
import_path: "webbrowser.open"
resources:
bookmarks:
type: text
description: "Common Python URLs"
content: |
Python Website: https://python.org
この設定でエージェントを使用します:
from llmling import RuntimeConfig
from llmling_agent import LLMlingAgent
from pydantic import BaseModel
class WebResult(BaseModel):
opened_url: str
success: bool
async with RuntimeConfig.open("config.yml") as runtime:
agent = LLMlingAgent[WebResult](runtime)
result = await agent.run(
"Load the bookmarks resource and open the Python website URL"
)
print(f"Opened: {result.data.opened_url}")
エージェントは次の処理を行います:
- ブックマークリソースを読み込みます
- Python のウェブサイト URL を抽出します
open_urlツールを使用して URL を開きます- 構造化された結果を返します
3. サーバーの使用方法
Zed Editor を使用する場合
settings.json で LLMLing をコンテキストサーバーとして追加します:
{
"context_servers": {
"llmling": {
"command": {
"env": {},
"label": "llmling",
"path": "uvx",
"args": [
"mcp-server-llmling@latest",
"start",
"path/to/your/config.yml",
"--zed-mode"
]
},
"settings": {}
}
}
}
Claude Desktop を使用する場合
claude_desktop_config.json で LLMLing を設定します:
{
"mcpServers": {
"llmling": {
"command": "uvx",
"args": [
"mcp-server-llmling@latest",
"start",
"path/to/your/config.yml"
],
"env": {}
}
}
}
サーバーを手動で起動する場合
コマンドラインからサーバーを直接起動します:
# Latest version
uvx mcp-server-llmling@latest start path/to/your/config.yml
リソース
リソースは、さまざまなソースからデータを読み込み、前処理するコンテンツプロバイダーです。
基本的なリソースの種類
global_config: # declare dependencies if used for tools or function prompts
requirements: ["myapp"]
scripts:
- "https://gist.githubusercontent.com/.../get_readme.py"
resources:
# Load and watch a file or directory
python_files:
type: path
path: "./src/**/*.py" # Glob patterns supported
watch: # Optional file watching
enabled: true
patterns:
- "*.py"
- "!**/__pycache__/**" # Exclude patterns with !
processors: # Optional processing steps
- name: format_python
- name: add_header
required: false # Optional step
# Static text content
system_prompt:
type: text
content: |
You are a code reviewer specialized in Python.
Focus on these aspects:
- Code style (PEP8)
- Best practices
- Performance
- Security
# Execute CLI commands
git_changes:
type: cli
command: "git diff HEAD~1" # String or list of args
shell: true # Use shell for command
cwd: "./src" # Optional working directory
timeout: 5.0 # Optional timeout in seconds
# Load Python source code
utils_module:
type: source
import_path: myapp.utils
recursive: true # Include submodules
include_tests: false # Exclude test files
# Execute Python callables
system_info:
type: callable
import_path: platform.uname
keyword_args: # Optional arguments
aliased: true
リソースグループ
関連するリソースをグループ化して、簡単にアクセスできるようにします:
resource_groups:
code_review:
- python_files
- git_changes
- system_prompt
documentation:
- architecture
- utils_module
ファイルの監視
ファイル監視をサポートするリソース(path、image)は、変更を検出するように設定できます:
resources:
config_files:
type: path
path: "./config"
watch:
enabled: true
patterns: # .gitignore style patterns
- "*.yml"
- "*.yaml"
- "!.private/**" # Exclude private files
ignore_file: ".gitignore" # Use existing ignore file
リソースの処理
リソースは、プロセッサーのパイプラインを通じて処理できます:
# First define processors
context_processors:
uppercase:
type: function
import_path: myapp.processors.to_upper
async_execution: false # Sync function
# Then use them in resources
resources:
processed_file:
type: path
path: "./input.txt"
processors:
- name: uppercase
プロンプト
プロンプトは、引数を指定してフォーマットできるメッセージテンプレートです。LLMLing は、宣言型の YAML プロンプトと関数ベースのプロンプトの両方をサポートしています。
YAML ベースのプロンプト
prompts:
code_review:
description: "Review Python code changes"
messages:
- role: system
content: |
You are a Python code reviewer. Focus on:
- Code style (PEP8)
- Best practices
- Performance
- Security
Always structure your review as:
1. Summary
2. Issues Found
3. Suggestions
- role: user
content: |
Review the following code changes:
{code}
Focus areas: {focus_areas}
arguments:
- name: code
description: "Code to review"
required: true
- name: focus_areas
description: "Specific areas to focus on (one of: style, security, performance)"
required: false
default: "style"
関数ベースのプロンプト
関数ベースのプロンプトでは、より細かく制御でき、自動補完も利用できます:
prompts:
analyze_code:
# Import path to the prompt function
import_path: myapp.prompts.code_analysis
# Optional overrides
name: "Code Analysis"
description: "Analyze Python code structure and complexity"
# Optional message template override
template: |
Analyze this code: {code}
Focus on: {focus}
# Auto-completion functions for arguments
completions:
focus: myapp.prompts.get_analysis_focus_options
# myapp/prompts/code_analysis.py
from typing import Literal
FocusArea = Literal["complexity", "dependencies", "typing"]
def code_analysis(
code: str,
focus: FocusArea = "complexity",
include_metrics: bool = True
) -> list[dict[str, str]]:
"""Analyze Python code structure and complexity.
Args:
code: Python source code to analyze
focus: Analysis focus area (one of: complexity, dependencies, typing)
include_metrics: Whether to include numeric metrics
"""
# Function will be converted to a prompt automatically
...
def get_analysis_focus_options(current: str) -> list[str]:
"""Provide auto-completion for focus argument."""
options = ["complexity", "dependencies", "typing"]
return [opt for opt in options if opt.startswith(current)]
メッセージのコンテンツタイプ
プロンプトでは、さまざまなコンテンツタイプをサポートしています:
prompts:
document_review:
messages:
# Text content
- role: system
content: "You are a document reviewer..."
# Resource reference
- role: user
content:
type: resource
content: "document://main.pdf"
alt_text: "Main document content"
# Image content
- role: user
content:
type: image_url
content: "https://example.com/diagram.png"
alt_text: "System architecture diagram"
引数の検証
プロンプトは、フォーマットする前に引数を検証します:
prompts:
analyze:
messages:
- role: user
content: "Analyze with level {level}"
arguments:
- name: level
description: "Analysis depth (one of: basic, detailed, full)"
required: true
# Will be used for validation and auto-completion
type_hint: Literal["basic", "detailed", "full"]
ツール
ツールは、LLM が呼び出せる Python の関数またはクラスです。カスタム機能を追加して LLM の能力を拡張する、安全な方法を提供します。
基本的なツール設定
tools:
# Function-based tool
analyze_code:
import_path: myapp.tools.code.analyze
description: "Analyze Python code structure and metrics"
# Class-based tool
browser:
import_path: llmling.tools.browser.BrowserTool
description: "Control web browser for research"
# Override tool name
code_metrics:
import_path: myapp.tools.analyze_complexity
name: "Analyze Code Complexity"
description: "Calculate code complexity metrics"
# Include pre-built tool collections
toolsets:
- llmling.code # Code analysis tools
- llmling.web # Web/browser tools
ツールセット
ツールセットとは、その名のとおり、ツールの集合です。現在、LLMling は以下をサポートしています:
- 拡張ポイントシステム
- OpenAPI エンドポイント
- クラスベースのツールセット
関数ベースのツール
任意の Python 関数からツールを作成できます:
# myapp/tools/code.py
from typing import Any
import ast
async def analyze(
code: str,
include_metrics: bool = True
) -> dict[str, Any]:
"""Analyze Python code structure and complexity.
Args:
code: Python source code to analyze
include_metrics: Whether to include numeric metrics
Returns:
Dictionary with analysis results
"""
tree = ast.parse(code)
return {
"classes": len([n for n in ast.walk(tree) if isinstance(n, ast.ClassDef)]),
"functions": len([n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)]),
"complexity": _calculate_complexity(tree) if include_metrics else None
}
クラスベースのツール
複雑なツールは、クラスとして実装できます:
# myapp/tools/browser.py
from typing import Literal
from playwright.async_api import Page
from llmling.tools.base import BaseTool
class BrowserTool(BaseTool):
"""Tool for web browser automation."""
name = "browser"
description = "Control web browser to navigate and interact with web pages"
...
def get_tools(self):
return [self.open_url, self.click_button]
ツールコレクション(ツールセット)
関連するツールをグループ化して、再利用可能なコレクションにします:
# myapp/toolsets.py
from typing import Callable, Any
def get_mcp_tools() -> list[Callable[..., Any]]:
"""Entry point exposing tools to LLMling."""
from myapp.tools import (
analyze_code,
check_style,
count_tokens
)
return [
analyze_code,
check_style,
count_tokens
]
pyproject.toml では:
[project.entry-points.llmling]
tools = "llmling.testing:get_mcp_tools"
ツールの進捗報告
ツールはクライアントに進捗を報告できます:
from llmling.tools.base import BaseTool
class AnalysisTool(BaseTool):
name = "analyze"
description = "Analyze large codebase"
async def execute(
self,
path: str,
_meta: dict[str, Any] | None = None, # Progress tracking
) -> dict[str, Any]:
files = list(Path(path).glob("**/*.py"))
results = []
for i, file in enumerate(files):
# Report progress if meta information provided
if _meta and "progressToken" in _meta:
self.notify_progress(
token=_meta["progressToken"],
progress=i,
total=len(files),
description=f"Analyzing {file.name}"
)
results.append(await self._analyze_file(file))
return {"results": results}
ツールの完全な例
複数のツール機能を組み合わせた完全な例を紹介します:
# Configuration
tools:
# Basic function tool
analyze:
import_path: myapp.tools.code.analyze
# Class-based tool with lifecycle
browser:
import_path: myapp.tools.browser.BrowserTool
# Tool with progress reporting
batch_analysis:
import_path: myapp.tools.AnalysisTool
toolsets:
- llmling.code
- myapp.tools
# Tool implementation
from typing import Any
from pathlib import Path
from llmling.tools.base import BaseTool
class AnalysisTool(BaseTool):
"""Tool for batch code analysis with progress reporting."""
name = "batch_analysis"
description = "Analyze multiple Python files"
async def startup(self) -> None:
"""Initialize analysis engine."""
self.analyzer = await self._create_analyzer()
async def execute(
self,
path: str,
recursive: bool = True,
_meta: dict[str, Any] | None = None
) -> dict[str, Any]:
"""Execute batch analysis.
Args:
path: Directory to analyze
recursive: Whether to analyze subdirectories
_meta: Optional progress tracking metadata
"""
files = list(Path(path).glob("**/*.py" if recursive else "*.py"))
results = []
for i, file in enumerate(files, 1):
# Report progress
if _meta and "progressToken" in _meta:
self.notify_progress(
token=_meta["progressToken"],
progress=i,
total=len(files),
description=f"Analyzing {file.name}"
)
# Analyze file
try:
result = await self.analyzer.analyze_file(file)
results.append({
"file": str(file),
"metrics": result
})
except Exception as e:
results.append({
"file": str(file),
"error": str(e)
})
return {
"total_files": len(files),
"successful": len([r for r in results if "metrics" in r]),
"failed": len([r for r in results if "error" in r]),
"results": results
}
async def shutdown(self) -> None:
"""Clean up analysis engine."""
await self.analyzer.close()
詳細:(注意:以下はほとんどが AI によって生成された古い情報であり、正確性は保証されません) はじめに 簡単な例 使用方法 YAML 設定 CLI
コメント
AI アプリケーションが外部のツールやデータソースに統一的な方法で接続するためのオープンなプロトコルです。クライアントはモデルとの対話を担い、MCP サーバーはツール・リソース・プロンプトテンプレートを提供します。標準メッセージでやり取りするため、1 つのサーバーを複数のクライアントで再利用できます。