log-mcp
log-mcp-python
MCP(Model Context Protocol) 기반 원격 로그 조회 서비스, Python 구현.
이 프로젝트는 오픈소스 Log-MCP(Java 버전)의 재설계 및 구현입니다: 외부에는 완전히 동일한 MCP 도구 인터페이스(JSON-RPC 2.0, STDIO / HTTP 두 가지 전송 모드)를 제공하고, 내부적으로는 Python 관례에 따라 전체 아키텍처를 재구성했으며, 「로그 획득 방식」을 플러그형 실행 채널로 추상화했습니다 — 로그를 가져오는 구체적인 명령은 서비스가 일괄 구성하고, 명령을 실행하는 채널만 다양합니다.
특성
인터페이스 호환: 원래 Java 버전과 동일한 5개 MCP 도구(
search_logs/tail_logs/read_log_file/list_log_files/list_servers), 입력·출력 계약 일치.플러그형 실행 채널:
ssh— SSH 개인키 직접 연결(paramiko, 연결 풀 및 자동 재연결 포함)pyinfra— 기존 pyinfra 호스트 자산 재사용(@local,root@host:22등 호스트 spec 지원)local— 로컬 실행(개발 / 테스트)
명령 일괄 구성: 모든 로그 작업을 대상 머신에서 실행되는 하나의 셸 명령(
grep -n -A -B/tail -n/sed -n/find)으로 정규화하며, 실행 채널과 분리됩니다 — 새 채널은CommandExecutor.execute()만 구현하면 됩니다.보안: 매개변수 검증, 상대 경로 검증, 위험 문자 감지, 원본과 동일한 셸 작은따옴표 이스케이프.
경량 의존성: 핵심은
paramiko만 의존합니다.pyinfra는 선택적 의존성으로, pyinfra 채널을 사용할 때만 설치합니다.
Related MCP server: jakubs-mcp-tools
아키텍처
MCP 客户端(AI 助手 / IDE)
│ JSON-RPC 2.0
▼
mcp/ 传输与协议层(stdio_server / http_server / handler)
▼
tools.py 5 个工具的声明式定义(名称 + JSON Schema + 处理函数)
▼
service/ 业务编排层(参数校验 → 文件推导 → 命令构建 → 解析)
▼
executors/ 可插拔执行通道(ssh_key / pyinfra_exec / local + registry)
▼
目标服务器上的 shell 命令(grep / tail / sed / find)상세 설계는 docs/DESIGN.md를 참조하세요.
설치
pip install . # 核心功能(ssh + local 通道)
pip install .[pyinfra] # 需要 pyinfra 通道时
pip install .[dev] # 运行测试구성
config.example.json을 참조하세요. 원래 Java 버전의 config.json 구조와 호환되며, 다음과 같은 확장이 추가되었습니다:
각 서버는
connector필드로 실행 채널을 개별 지정합니다:ssh(기본값) /pyinfra/localpyinfra 채널은
pyinfraHost(전체 호스트 spec, 예:root@192.168.5.20:22또는@local)와pyinfraData(pyinfra에 전달되는 호스트 데이터, 예:ssh_key)를 지원합니다문자열은
${VAR}환경 변수 플레이스홀더를 지원합니다(정의되지 않으면 원래대로 유지)
{
"servers": [
{
"name": "ssh-server",
"connector": "ssh",
"host": "192.168.5.169",
"port": 22,
"username": "root",
"privateKeyPath": "${SSH_KEY_PATH}",
"logRootPath": "/home/docker/logs/myapp/",
"default": true
},
{
"name": "pyinfra-server",
"connector": "pyinfra",
"pyinfraHost": "root@192.168.5.20:22",
"pyinfraData": { "ssh_key": "/root/.ssh/id_rsa" },
"logRootPath": "/var/logs/app/"
},
{
"name": "dev-local",
"connector": "local",
"logRootPath": "/tmp/logs/"
}
],
"logLevels": ["info", "warn", "error", "debug"],
"logFilePattern": "{level}/log-{level}-{date}.{seq}.log"
}주요 필드 설명:
필드 | 설명 |
| 실행 채널: |
| 로그 루트 디렉터리(상대 경로 검증의 기준) |
| 로그 파일 명명 패턴, |
| SSH 연결 풀(연결 수 상한 / 타임아웃 / 재시도) |
| 쿼리 기본값 및 상한(maxResults / maxReadLines / contextLines 등) |
실행
# STDIO 模式(MCP 客户端拉起,默认)
log-mcp --config config.json
# HTTP 模式(独立部署,端口默认 8892,路径 / 与 /mcp,健康检查 GET /health)
log-mcp --config config.json --transport http --port 8892환경 변수도 지원합니다: LOG_CONFIG, TRANSPORT_MODE, SERVER_PORT.
MCP 클라이언트 연동(HTTP 모드 예시):
{
"mcpServers": {
"log-mcp": {
"url": "http://your-host:8892/mcp"
}
}
}STDIO 모드 연동:
{
"mcpServers": {
"log-mcp": {
"command": "log-mcp",
"args": ["--config", "/path/to/config.json"]
}
}
}MCP 도구
도구 | 설명 |
| 키워드(선택적 정규식)로 날짜·레벨을 넘나들며 로그를 검색하고, 앞뒤 컨텍스트 포함 |
| 지정된 레벨의 최신 N줄 로그 가져오기 |
| 지정된 로그 파일의 줄 구간 읽기 |
| 서버에서 사용 가능한 로그 파일 나열(크기 / 수정 시간) |
| 구성된 모든 서버 나열 |
호출 예시(HTTP):
curl -s -X POST http://127.0.0.1:8892/mcp -H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/call",
"params":{"name":"search_logs","arguments":{"keyword":"ERROR","levels":["error","info"]}}}'테스트
python -m pytest tests/ -q테스트 범위: 매개변수/경로 검증, 셸 이스케이프, 명령 구성, grep 출력 파싱(알려진 파일 결정적 파싱 포함), JSON-RPC 프로토콜 처리, 그리고 local / pyinfra(@local) 두 채널의 엔드투엔드 통합 테스트(총 100개 테스트 케이스).
License
Apache-2.0
This server cannot be deployed
Maintenance
Related MCP Connectors
Syslog receiver and MCP server for homelab log intelligence.
Syslog receiver and MCP server for homelab log intelligence.
Search your AI chat history (ChatGPT, Claude, Codex) from any MCP client. Remote, private, read-only
Termalin's hosted MCP server. Claude, ChatGPT or any MCP client runs commands, moves files over SFTP, queries databases and reads server metrics and monitoring alerts on your servers, keylessly through Termalin Connectors: no SSH key is handed over and no inbound port is opened. Per-host command policy and an audit log. Needs a termal.in Pro or Team account (new accounts start with a 14-day Pro trial).
Related MCP Servers
- AlicenseNot gradedqualityFmaintenanceExposes configured log files as MCP tools, enabling agents to list, query, and follow logs from local and SSH sources.MIT
- AlicenseNot gradedqualityFmaintenanceMCP server for infrastructure discovery and remote management, enabling SSH command execution, file transfer, log tailing, and machine/service inventory with a companion web dashboard.2MIT
- AlicenseNot gradedqualityDmaintenanceA set of MCP tools for parsing, filtering, analyzing, formatting, and computing stats on logs in common formats (JSON, Apache/Nginx, syslog, structured, custom regex).16 npm1MIT
- AlicenseAqualityAmaintenanceManage local/SSH/WinRM remote hosts via MCP, providing tools for exec, filesystem, screen, process, serial console, and configuration.7Apache 2.0