Skip to content
Back to search

mcphost

A CLI host application that enables Large Language Models (LLMs) to interact with external tools through the Model Context Protocol (MCP).

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/mark3labs--mcphost/badge.svg)](/listings/mark3labs--mcphost)

HTML

<a href="/listings/mark3labs--mcphost"><img src="/api/listings/mark3labs--mcphost/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

1. API Keys:

# For all providers (use --provider-api-key flag or these environment variables)
export OPENAI_API_KEY='your-openai-key'        # For OpenAI
export ANTHROPIC_API_KEY='your-anthropic-key'  # For Anthropic
export GOOGLE_API_KEY='your-google-key'        # For Google/Gemini

2. Ollama Setup: - Install Ollama from https://ollama.ai - Pull your desired model:

ollama pull mistral

- Ensure Ollama is running:

ollama serve

You can also configure the Ollama client using standard environment variables, such as `OLLAMA_HOST` for the Ollama base URL.

3. Google API Key (for Gemini):

export GOOGLE_API_KEY='your-api-key'

4. OpenAI Compatible Setup: - Get your API server base URL, API key and model name - Use `--provider-url` and `--provider-api-key` flags or set environment variables

5. Self-Signed Certificates (TLS): If your provider uses self-signed certificates (e.g., local Ollama with HTTPS), you can skip certificate verification:

mcphost --provider-url https://192.168.1.100:443 --tls-skip-verify

⚠️ **WARNING**: Only use `--tls-skip-verify` for development or when connecting to trusted servers with self-signed certificates. This disables TLS certificate verification and is insecure for production use.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 999 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # ⚠️ MCPHost is No Longer Actively Maintained
  2. **Active development on MCPHost has been stopped.** This project has been succeeded by [**Kit**](https://github.com/mark3labs/kit), which builds on the foundations of MCPHost with a more powerful and extensible architecture.
  3. 👉 **We recommend all users migrate to [Kit](https://github.com/mark3labs/kit).**
  4. This repository is now archived and will not receive further updates or bug fixes.
  5. ---
  6. # MCPHost 🤖
  7. A CLI host application that enables Large Language Models (LLMs) to interact with external tools through the Model Context Protocol (MCP). Currently supports Claude, OpenAI, Google Gemini, and Ollama models.
  8. Discuss the Project on [Discord](https://discord.gg/RqSS2NQVsY)
  9. ## Table of Contents
  10. - [Overview](#overview-)
  11. - [Features](#features-)
  12. - [Requirements](#requirements-)
  13. - [Environment Setup](#environment-setup-)
  14. - [Installation](#installation-)
  15. - [SDK Usage](#sdk-usage-)
  16. - [Configuration](#configuration-)
  17. - [MCP Servers](#mcp-servers)
  18. - [Environment Variable Substitution](#environment-variable-substitution)
  19. - [Simplified Configuration Schema](#simplified-configuration-schema)
  20. - [Tool Filtering](#tool-filtering)
  21. - [Legacy Configuration Support](#legacy-configuration-support)
  22. - [Transport Types](#transport-types)
  23. - [System Prompt](#system-prompt)
  24. - [Usage](#usage-)
  25. - [Interactive Mode](#interactive-mode-default)
  26. - [Script Mode](#script-mode)
  27. - [Hooks System](#hooks-system)
  28. - [Non-Interactive Mode](#non-interactive-mode)
  29. - [Model Generation Parameters](#model-generation-parameters)
  30. - [Available Models](#available-models)
  31. - [Examples](#examples)
  32. - [Flags](#flags)
  33. - [Authentication Subcommands](#authentication-subcommands)
  34. - [Configuration File Support](#configuration-file-support)
  35. - [Interactive Commands](#interactive-commands)
  36. - [Automation & Scripting](#automation--scripting-)
  37. - [MCP Server Compatibility](#mcp-server-compatibility-)
  38. - [Contributing](#contributing-)
  39. - [License](#license-)
  40. - [Acknowledgments](#acknowledgments-)
  41. ## Overview 🌟
  42. MCPHost acts as a host in the MCP client-server architecture, where:
  43. - **Hosts** (like MCPHost) are LLM applications that manage connections and interactions
  44. - **Clients** maintain 1:1 connections with MCP servers
  45. - **Servers** provide context, tools, and capabilities to the LLMs
  46. This architecture allows language models to:
  47. - Access external tools and data sources 🛠️
  48. - Maintain consistent context across interactions 🔄
  49. - Execute commands and retrieve information safely 🔒
  50. Currently supports:
  51. - Anthropic Claude models (Claude 3.5 Sonnet, Claude 3.5 Haiku, etc.)
  52. - OpenAI models (GPT-4, GPT-4 Turbo, GPT-3.5, etc.)
  53. - Google Gemini models (Gemini 2.0 Flash, Gemini 1.5 Pro, etc.)
  54. - Any Ollama-compatible model with function calling support
  55. - Any OpenAI-compatible API endpoint
  56. ## Features ✨
  57. - Interactive conversations with multiple AI models
  58. - **Non-interactive mode** for scripting and automation
  59. - **Script mode** for executable YAML-based automation scripts
  60. - Support for multiple concurrent MCP servers
  61. - **Tool filtering** with `allowedTools` and `excludedTools` per server
  62. - Dynamic tool discovery and integration
  63. - Tool calling capabilities across all supported models
  64. - Configurable MCP server locations and arguments
  65. - Consistent command interface across model types
  66. - Configurable message history window for context management
  67. - **OAuth authentication** support for Anthropic (alternative to API keys)
  68. - **Hooks system** for custom integrations and security policies
  69. - **Environment variable substitution** in configs and scripts
  70. - **Builtin servers** for common functionality (filesystem, bash, todo, http)
  71. ## Requirements 📋
  72. - Go 1.23 or later
  73. - For OpenAI/Anthropic: API key for the respective provider
  74. - For Ollama: Local Ollama installation with desired models
  75. - For Google/Gemini: Google API key (see https://aistudio.google.com/app/apikey)
  76. - One or more MCP-compatible tool servers
  77. ## Environment Setup 🔧
  78. 1. API Keys:
  79. ```bash
  80. # For all providers (use --provider-api-key flag or these environment variables)
  81. export OPENAI_API_KEY='your-openai-key' # For OpenAI
  82. export ANTHROPIC_API_KEY='your-anthropic-key' # For Anthropic
  83. export GOOGLE_API_KEY='your-google-key' # For Google/Gemini
  84. ```
  85. 2. Ollama Setup:
  86. - Install Ollama from https://ollama.ai
  87. - Pull your desired model:
  88. ```bash
  89. ollama pull mistral
  90. ```
  91. - Ensure Ollama is running:
  92. ```bash
  93. ollama serve
  94. ```
  95. You can also configure the Ollama client using standard environment variables, such as `OLLAMA_HOST` for the Ollama base URL.
  96. 3. Google API Key (for Gemini):
  97. ```bash
  98. export GOOGLE_API_KEY='your-api-key'
  99. ```
  100. 4. OpenAI Compatible Setup:
  101. - Get your API server base URL, API key and model name
  102. - Use `--provider-url` and `--provider-api-key` flags or set environment variables
  103. 5. Self-Signed Certificates (TLS):
  104. If your provider uses self-signed certificates (e.g., local Ollama with HTTPS), you can skip certificate verification:
  105. ```bash
  106. mcphost --provider-url https://192.168.1.100:443 --tls-skip-verify
  107. ```
  108. ⚠️ **WARNING**: Only use `--tls-skip-verify` for development or when connecting to trusted servers with self-signed certificates. This disables TLS certificate verification and is insecure for production use.
  109. ## Installation 📦
  110. ```bash
  111. go install github.com/mark3labs/mcphost@latest
  112. ```
  113. ## SDK Usage 🛠️
  114. MCPHost also provides a Go SDK for programmatic access without spawning OS processes. The SDK maintains identical behavior to the CLI, including configuration loading, environment variables, and defaults.
  115. ### Quick Example
  116. ```go
  117. package main
  118. import (
  119. "context"
  120. "fmt"
  121. "github.com/mark3labs/mcphost/sdk"
  122. )
  123. func main() {
  124. ctx := context.Background()
  125. // Create MCPHost instance with default configuration
  126. host, err := sdk.New(ctx, nil)
  127. if err != nil {
  128. panic(err)
  129. }
  130. defer host.Close()
  131. // Send a prompt and get response
  132. response, err := host.Prompt(ctx, "What is 2+2?")
  133. if err != nil {
  134. panic(err)
  135. }
  136. fmt.Println(response)
  137. }
  138. ```
  139. ### SDK Features
  140. - ✅ Programmatic access without spawning processes
  141. - ✅ Identical configuration behavior to CLI
  142. - ✅ Session management (save/load/clear)
  143. - ✅ Tool execution callbacks for monitoring
  144. - ✅ Streaming support
  145. - ✅ Full compatibility with all providers and MCP servers
  146. For detailed SDK documentation, examples, and API reference, see the [SDK README](sdk/README.md).
  147. ## Configuration ⚙️
  148. ### MCP Servers
  149. MCPHost will automatically create a configuration file in your home directory if it doesn't exist. It looks for config files in this order:
  150. - `.mcphost.yml` or `.mcphost.json` (preferred)
  151. - `.mcp.yml` or `.mcp.json` (backwards compatibility)
  152. **Config file locations by OS:**
  153. - **Linux/macOS**: `~/.mcphost.yml`, `~/.mcphost.json`, `~/.mcp.yml`, `~/.mcp.json`
  154. - **Windows**: `%USERPROFILE%\.mcphost.yml`, `%USERPROFILE%\.mcphost.json`, `%USERPROFILE%\.mcp.yml`, `%USERPROFILE%\.mcp.json`
  155. You can also specify a custom location using the `--config` flag.
  156. ### Environment Variable Substitution
  157. MCPHost supports environment variable substitution in both config files and script frontmatter using the syntax:
  158. - **`${env://VAR}`** - Required environment variable (fails if not set)
  159. - **`${env://VAR:-default}`** - Optional environment variable with default value
  160. This allows you to keep sensitive information like API keys in environment variables while maintaining flexible configuration.
  161. **Example:**
  162. ```yaml
  163. mcpServers:
  164. github:
  165. type: local
  166. command: ["docker", "run", "-i", "--rm", "-e", "GITHUB_PERSONAL_ACCESS_TOKEN=${env://GITHUB_TOKEN}", "ghcr.io/github/github-mcp-server"]
  167. environment:
  168. DEBUG: "${env://DEBUG:-false}"
  169. LOG_LEVEL: "${env://LOG_LEVEL:-info}"
  170. model: "${env://MODEL:-anthropic/claude-sonnet-4-5-20250929}"
  171. provider-api-key: "${env://OPENAI_API_KEY}" # Required - will fail if not set
  172. ```
  173. **Usage:**
  174. ```bash
  175. # Set required environment variables
  176. export GITHUB_TOKEN="ghp_your_token_here"
  177. export OPENAI_API_KEY="your_openai_key"
  178. # Optionally override defaults
  179. export DEBUG="true"
  180. export MODEL="openai/gpt-4"
  181. # Run mcphost
  182. mcphost
  183. ```
  184. ### Simplified Configuration Schema
  185. MCPHost now supports a simplified configuration schema with three server types:
  186. #### Local Servers
  187. For local MCP servers that run commands on your machine:
  188. ```json
  189. {
  190. "mcpServers": {
  191. "filesystem": {
  192. "type": "local",
  193. "command": ["npx", "@modelcontextprotocol/server-filesystem", "${env://WORK_DIR:-/tmp}"],
  194. "environment": {
  195. "DEBUG": "${env://DEBUG:-false}",
  196. "LOG_LEVEL": "${env://LOG_LEVEL:-info}",
  197. "API_TOKEN": "${env://FS_API_TOKEN}"
  198. },
  199. "allowedTools": ["read_file", "write_file"],
  200. "excludedTools": ["delete_file"]
  201. },
  202. "github": {
  203. "type": "local",
  204. "command": ["docker", "run", "-i", "--rm", "-e", "GITHUB_PERSONAL_ACCESS_TOKEN=${env://GITHUB_TOKEN}", "ghcr.io/github/github-mcp-server"],
  205. "environment": {
  206. "DEBUG": "${env://DEBUG:-false}"
  207. }
  208. },
  209. "sqlite": {
  210. "type": "local",
  211. "command": ["uvx", "mcp-server-sqlite", "--db-path", "${env://DB_PATH:-/tmp/foo.db}"],
  212. "environment": {
  213. "SQLITE_DEBUG": "${env://DEBUG:-0}",
  214. "DATABASE_URL": "${env://DATABASE_URL:-sqlite:///tmp/foo.db}"
  215. }
  216. }
  217. }
  218. }
  219. ```
  220. Each local server entry requires:
  221. - `type`: Must be set to `"local"`
  222. - `command`: Array containing the command and all its arguments
  223. - `environment`: (Optional) Object with environment variables as key-value pairs
  224. - `allowedTools`: (Optional) Array of tool names to include (whitelist)
  225. - `excludedTools`: (Optional) Array of tool names to exclude (blacklist)
  226. #### Remote Servers
  227. For remote MCP servers accessible via HTTP:
  228. ```json
  229. {
  230. "mcpServers": {
  231. "websearch": {
  232. "type": "remote",
  233. "url": "${env://WEBSEARCH_URL:-https://api.example.com/mcp}",
  234. "headers": ["Authorization: Bearer ${env://WEBSEARCH_TOKEN}"]
  235. },
  236. "weather": {
  237. "type": "remote",
  238. "url": "${env://WEATHER_URL:-https://weather-mcp.example.com}"
  239. }
  240. }
  241. }
  242. ```
  243. Each remote server entry requires:
  244. - `type`: Must be set to `"remote"`
  245. - `url`: The URL where the MCP server is accessible
  246. - `headers`: (Optional) Array of HTTP headers for authentication and custom headers
  247. Remote servers automatically use the StreamableHTTP transport for optimal performance.
  248. #### Builtin Servers
  249. For builtin MCP servers that run in-process for optimal performance:
  250. ```json
  251. {
  252. "mcpServers": {
  253. "filesystem": {
  254. "type": "builtin",
  255. "name": "fs",
  256. "options": {
  257. "allowed_directories": ["${env://WORK_DIR:-/tmp}", "${env://HOME}/documents"]
  258. },
  259. "allowedTools": ["read_file", "write_file", "list_directory"]
  260. },
  261. "filesystem-cwd": {
  262. "type": "builtin",
  263. "name": "fs"
  264. }
  265. }
  266. }
  267. ```
  268. Each builtin server entry requires:
  269. - `type`: Must be set to `"builtin"`
  270. - `name`: Internal name of the builtin server (e.g., `"fs"` for filesystem)
  271. - `options`: Configuration options specific to the builtin server
  272. **Available Builtin Servers:**
  273. - `fs` (filesystem): Secure filesystem access with configurable allowed directories
  274. - `allowed_directories`: Array of directory paths that the server can access (defaults to current working directory if not specified)
  275. - `bash`: Execute bash commands with security restrictions and timeout controls
  276. - No configuration options required
  277. - `todo`: Manage ephemeral todo lists for task tracking during sessions
  278. - No configuration options required (todos are stored in memory and reset on restart)
  279. - `http`: Fetch web content and convert to text, markdown, or HTML formats
  280. - Tools: `fetch` (fetch and convert web content), `fetch_summarize` (fetch and summarize web content using AI), `fetch_extract` (fetch and extract specific data using AI), `fetch_filtered_json` (fetch JSON and filter using gjson path syntax)
  281. - No configuration options required
  282. #### Builtin Server Examples
  283. ```json
  284. {
  285. "mcpServers": {
  286. "filesystem": {
  287. "type": "builtin",
  288. "name": "fs",
  289. "options": {
  290. "allowed_directories": ["/tmp", "/home/user/documents"]
  291. }
  292. },
  293. "bash-commands": {
  294. "type": "builtin",
  295. "name": "bash"
  296. },
  297. "task-manager": {
  298. "type": "builtin",
  299. "name": "todo"
  300. },
  301. "web-fetcher": {
  302. "type": "builtin",
  303. "name": "http"
  304. }
  305. }
  306. }
  307. ```
  308. ### Tool Filtering
  309. All MCP server types support tool filtering to restrict which tools are available:
  310. - **`allowedTools`**: Whitelist - only specified tools are available from the server
  311. - **`excludedTools`**: Blacklist - all tools except specified ones are available
  312. ```json
  313. {
  314. "mcpServers": {
  315. "filesystem-readonly": {
  316. "type": "builtin",
  317. "name": "fs",
  318. "allowedTools": ["read_file", "list_directory"]
  319. },
  320. "filesystem-safe": {
  321. "type": "local",
  322. "command": ["npx", "@modelcontextprotocol/server-filesystem", "/tmp"],
  323. "excludedTools": ["delete_file"]
  324. }
  325. }
  326. }
  327. ```
  328. **Note**: `allowedTools` and `excludedTools` are mutually exclusive - you can only use one per server.
  329. ### Legacy Configuration Support
  330. MCPHost maintains full backward compatibility with the previous configuration format. **Note**: A recent bug fix improved legacy stdio transport reliability for external MCP servers (Docker, NPX, etc.).
  331. #### Legacy STDIO Format
  332. ```json
  333. {
  334. "mcpServers": {
  335. "sqlite": {
  336. "command": "uvx",
  337. "args": ["mcp-server-sqlite", "--db-path", "/tmp/foo.db"],
  338. "env": {
  339. "DEBUG": "true"
  340. }
  341. }
  342. }
  343. }
  344. ```
  345. #### Legacy SSE Format
  346. ```json
  347. {
  348. "mcpServers": {
  349. "server_name": {
  350. "url": "http://some_host:8000/sse",
  351. "headers": ["Authorization: Bearer my-token"]
  352. }
  353. }
  354. }
  355. ```
  356. #### Legacy Docker/Container Format
  357. ```json
  358. {
  359. "mcpServers": {
  360. "phalcon": {
  361. "command": "docker",
  362. "args": [
  363. "run",
  364. "-i",
  365. "--rm",
  366. "ghcr.io/mark3labs/phalcon-mcp:latest",
  367. "serve"
  368. ]
  369. }
  370. }
  371. }
  372. ```
  373. #### Legacy Streamable HTTP Format
  374. ```json
  375. {
  376. "mcpServers": {
  377. "websearch": {
  378. "transport": "streamable",
  379. "url": "https://api.example.com/mcp",
  380. "headers": ["Authorization: Bearer your-api-token"]
  381. }
  382. }
  383. }
  384. ```
  385. ### Transport Types
  386. MCPHost supports four transport types:
  387. - **`stdio`**: Launches a local process and communicates via stdin/stdout (used by `"local"` servers)
  388. - **`sse`**: Connects to a server using Server-Sent Events (legacy format)
  389. - **`streamable`**: Connects to a server using Streamable HTTP protocol (used by `"remote"` servers)
  390. - **`inprocess`**: Runs builtin servers in-process for optimal performance (used by `"builtin"` servers)
  391. The simplified schema automatically maps:
  392. - `"local"` type → `stdio` transport
  393. - `"remote"` type → `streamable` transport
  394. - `"builtin"` type → `inprocess` transport
  395. ### System Prompt
  396. You can specify a custom system prompt using the `--system-prompt` flag. You can either:
  397. 1. **Pass the prompt directly as text:**
  398. ```bash
  399. mcphost --system-prompt "You are a helpful assistant that responds in a friendly tone."
  400. ```
  401. 2. **Pass a path to a text file containing the prompt:**
  402. ```bash
  403. mcphost --system-prompt ./prompts/assistant.md
  404. ```
  405. Example `assistant.md` file:
  406. ```markdown
  407. You are a helpful coding assistant.
  408. Please:
  409. - Write clean, readable code
  410. - Include helpful comments
  411. - Follow best practices
  412. - Explain your reasoning
  413. ```
  414. ## Usage 🚀
  415. MCPHost is a CLI tool that allows you to interact with various AI models through a unified interface. It supports various tools through MCP servers and can run in both interactive and non-interactive modes.
  416. ### Interactive Mode (Default)
  417. Start an interactive conversation session:
  418. ```bash
  419. mcphost
  420. ```
  421. ### Script Mode
  422. Run executable YAML-based automation scripts with variable substitution support:
  423. ```bash
  424. # Using the script subcommand
  425. mcphost script myscript.sh
  426. # With variables
  427. mcphost script myscript.sh --args:directory /tmp --args:name "John"
  428. # Direct execution (if executable and has shebang)
  429. ./myscript.sh
  430. ```
  431. #### Script Format
  432. Scripts combine YAML configuration with prompts in a single executable file. The configuration must be wrapped in frontmatter delimiters (`---`). You can either include the prompt in the YAML configuration or place it after the closing frontmatter delimiter:
  433. ```yaml
  434. #!/usr/bin/env -S mcphost script
  435. ---
  436. # This script uses the container-use MCP server from https://github.com/dagger/container-use
  437. mcpServers:
  438. container-use:
  439. type: "local"
  440. command: ["cu", "stdio"]
  441. prompt: |
  442. Create 2 variations of a simple hello world app using Flask and FastAPI.
  443. Each in their own environment. Give me the URL of each app
  444. ---
  445. ```
  446. Or alternatively, omit the `prompt:` field and place the prompt after the frontmatter:
  447. ```yaml
  448. #!/usr/bin/env -S mcphost script
  449. ---
  450. # This script uses the container-use MCP server from https://github.com/dagger/container-use
  451. mcpServers:
  452. container-use:
  453. type: "local"
  454. command: ["cu", "stdio"]
  455. ---
  456. Create 2 variations of a simple hello world app using Flask and FastAPI.
  457. Each in their own environment. Give me the URL of each app
  458. ```
  459. #### Variable Substitution
  460. Scripts support both environment variable substitution and script argument substitution:
  461. 1. **Environment Variables**: `${env://VAR}` and `${env://VAR:-default}` - Processed first
  462. 2. **Script Arguments**: `${variable}` and `${variable:-default}` - Processed after environment variables
  463. Variables can be provided via command line arguments:
  464. ```bash
  465. # Script with variables
  466. mcphost script myscript.sh --args:directory /tmp --args:name "John"
  467. ```
  468. ##### Variable Syntax
  469. MCPHost supports these variable syntaxes:
  470. 1. **Required Environment Variables**: `${env://VAR}` - Must be set in environment
  471. 2. **Optional Environment Variables**: `${env://VAR:-default}` - Uses default if not set
  472. 3. **Required Script Arguments**: `${variable}` - Must be provided via `--args:variable value`
  473. 4. **Optional Script Arguments**: `${variable:-default}` - Uses default if not provided
  474. Example script with mixed environment variables and script arguments:
  475. ```yaml
  476. #!/usr/bin/env -S mcphost script
  477. ---
  478. mcpServers:
  479. github:
  480. type: "local"
  481. command: ["gh", "api"]
  482. environment:
  483. GITHUB_TOKEN: "${env://GITHUB_TOKEN}"
  484. DEBUG: "${env://DEBUG:-false}"
  485. filesystem:
  486. type: "local"
  487. command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "${env://WORK_DIR:-/tmp}"]
  488. model: "${env://MODEL:-anthropic/claude-sonnet-4-5-20250929}"
  489. ---
  490. Hello ${name:-World}! Please list ${repo_type:-public} repositories for user ${username}.
  491. Working directory is ${env://WORK_DIR:-/tmp}.
  492. Use the ${command:-gh} command to fetch ${count:-10} repositories.
  493. ```
  494. ##### Usage Examples
  495. ```bash
  496. # Set environment variables first
  497. export GITHUB_TOKEN="ghp_your_token_here"
  498. export DEBUG="true"
  499. export WORK_DIR="/home/user/projects"
  500. # Uses env vars and defaults: name="World", repo_type="public", command="gh", count="10"
  501. mcphost script myscript.sh
  502. # Override specific script arguments
  503. mcphost script myscript.sh --args:name "John" --args:username "alice"
  504. # Override multiple script arguments
  505. mcphost script myscript.sh --args:name "John" --args:username "alice" --args:repo_type "private"
  506. # Mix of env vars, provided args, and default values
  507. mcphost script myscript.sh --args:name "Alice" --args:command "gh api" --args:count "5"
  508. ```
  509. ##### Default Value Features
  510. - **Empty defaults**: `${var:-}` - Uses empty string if not provided
  511. - **Complex defaults**: `${path:-/tmp/default/path}` - Supports paths, URLs, etc.
  512. - **Spaces in defaults**: `${msg:-Hello World}` - Supports spaces in default values
  513. - **Backward compatibility**: Existing `${variable}` syntax continues to work unchanged
  514. **Important**:
  515. - Environment variables without defaults (e.g., `${env://GITHUB_TOKEN}`) are required and must be set in the environment
  516. - Script arguments without defaults (e.g., `${username}`) are required and must be provided via `--args:variable value` syntax
  517. - Variables with defaults are optional and will use their default value if not provided
  518. - Environment variables are processed first, then script arguments
  519. #### Script Features
  520. - **Executable**: Use shebang line for direct execution (`#!/usr/bin/env -S mcphost script`)
  521. - **YAML Configuration**: Define MCP servers directly in the script
  522. - **Embedded Prompts**: Include the prompt in the YAML
  523. - **Variable Substitution**: Use `${variable}` and `${variable:-default}` syntax with `--args:variable value`
  524. - **Variable Validation**: Missing required variables cause script to exit with helpful error
  525. - **Interactive Mode**: If prompt is empty, drops into interactive mode (handy for setup scripts)
  526. - **Config Fallback**: If no `mcpServers` defined, uses default config
  527. - **Tool Filtering**: Supports `allowedTools`/`excludedTools` per server
  528. - **Clean Exit**: Automatically exits after completion
  529. **Note**: The shebang line requires `env -S` to handle the multi-word command `mcphost script`. This is supported on most modern Unix-like systems.
  530. #### Script Examples
  531. See `examples/scripts/` for sample scripts:
  532. - `example-script.sh` - Script with custom MCP servers
  533. - `simple-script.sh` - Script using default config fallback
  534. ### Hooks System
  535. MCPHost supports a powerful hooks system that allows you to execute custom commands at specific points during execution. This enables security policies, logging, custom integrations, and automated workflows.
  536. #### Quick Start
  537. 1. Initialize a hooks configuration:
  538. ```bash
  539. mcphost hooks init
  540. ```
  541. 2. View active hooks:
  542. ```bash
  543. mcphost hooks list
  544. ```
  545. 3. Validate your configuration:
  546. ```bash
  547. mcphost hooks validate
  548. ```
  549. #### Configuration
  550. Hooks are configured in YAML files with the following precedence (highest to lowest):
  551. - `.mcphost/hooks.yml` (project-specific hooks)
  552. - `$XDG_CONFIG_HOME/mcphost/hooks.yml` (user global hooks, defaults to `~/.config/mcphost/hooks.yml`)
  553. Example configuration:
  554. ```yaml
  555. hooks:
  556. PreToolUse:
  557. - matcher: "bash"
  558. hooks:
  559. - type: command
  560. command: "/usr/local/bin/validate-bash.py"
  561. timeout: 5
  562. UserPromptSubmit:
  563. - hooks:
  564. - type: command
  565. command: "~/.mcphost/hooks/log-prompt.sh"
  566. ```
  567. #### Available Hook Events
  568. - **PreToolUse**: Before any tool execution (bash, fetch, todo, MCP tools)
  569. - **PostToolUse**: After tool execution completes
  570. - **UserPromptSubmit**: When user submits a prompt
  571. - **Stop**: When the agent finishes responding
  572. - **SubagentStop**: When a subagent (Task tool) finishes
  573. - **Notification**: When MCPHost sends notifications
  574. #### Security
  575. ⚠️ **WARNING**: Hooks execute arbitrary commands on your system. Only use hooks from trusted sources and always review hook commands before enabling them.
  576. To temporarily disable all hooks, use the `--no-hooks` flag:
  577. ```bash
  578. mcphost --no-hooks
  579. ```
  580. See the example hook scripts in `examples/hooks/`:
  581. - `bash-validator.py` - Validates and blocks dangerous bash commands
  582. - `prompt-logger.sh` - Logs all user prompts with timestamps
  583. - `mcp-monitor.py` - Monitors and enforces policies on MCP tool usage
  584. ### Non-Interactive Mode
  585. Run a single prompt and exit - perfect for scripting and automation:
  586. ```bash
  587. # Basic non-interactive usage
  588. mcphost -p "What is the weather like today?"
  589. # Quiet mode - only output the AI response (no UI elements)
  590. mcphost -p "What is 2+2?" --quiet
  591. # Use with different models
  592. mcphost -m ollama/qwen2.5:3b -p "Explain quantum computing" --quiet
  593. ```
  594. ### Model Generation Parameters
  595. MCPHost supports fine-tuning model behavior through various parameters:
  596. ```bash
  597. # Control response length
  598. mcphost -p "Explain AI" --max-tokens 1000
  599. # Adjust creativity (0.0 = focused, 1.0 = creative)
  600. mcphost -p "Write a story" --temperature 0.9
  601. # Control diversity with nucleus sampling
  602. mcphost -p "Generate ideas" --top-p 0.8
  603. # Limit token choices for more focused responses
  604. mcphost -p "Answer precisely" --top-k 20
  605. # Set custom stop sequences
  606. mcphost -p "Generate code" --stop-sequences "```","END"
  607. ```
  608. These parameters work with all supported providers (OpenAI, Anthropic, Google, Ollama) where supported by the underlying model.
  609. ### Available Models
  610. Models can be specified using the `--model` (`-m`) flag:
  611. - **Anthropic Claude** (default): `anthropic/claude-sonnet-4-5-20250929`, `anthropic/claude-3-5-sonnet-latest`, `anthropic/claude-3-5-haiku-latest`
  612. - **OpenAI**: `openai/gpt-4`, `openai/gpt-4-turbo`, `openai/gpt-3.5-turbo`
  613. - **Google Gemini**: `google/gemini-2.0-flash`, `google/gemini-1.5-pro`
  614. - **Ollama models**: `ollama/llama3.2`, `ollama/qwen2.5:3b`, `ollama/mistral`
  615. - **OpenAI-compatible**: Any model via custom endpoint with `--provider-url`
  616. ### Examples
  617. #### Interactive Mode
  618. ```bash
  619. # Use Ollama with Qwen model
  620. mcphost -m ollama/qwen2.5:3b
  621. # Use OpenAI's GPT-4
  622. mcphost -m openai/gpt-4
  623. # Use OpenAI-compatible model with custom URL and API key
  624. mcphost --model openai/<your-model-name> \
  625. --provider-url <your-base-url> \
  626. --provider-api-key <your-api-key>
  627. ```
  628. #### Non-Interactive Mode
  629. ```bash
  630. # Single prompt with full UI
  631. mcphost -p "List files in the current directory"
  632. # Compact mode for cleaner output without fancy styling
  633. mcphost -p "List files in the current directory" --compact
  634. # Quiet mode for scripting (only AI response output, no UI elements)
  635. mcphost -p "What is the capital of France?" --quiet
  636. # Use in shell scripts
  637. RESULT=$(mcphost -p "Calculate 15 * 23" --quiet)
  638. echo "The answer is: $RESULT"
  639. # Pipe to other commands
  640. mcphost -p "Generate a random UUID" --quiet | tr '[:lower:]' '[:upper:]'
  641. ```
  642. ### Flags
  643. - `--provider-url string`: Base URL for the provider API (applies to OpenAI, Anthropic, Ollama, and Google)
  644. - `--provider-api-key string`: API key for the provider (applies to OpenAI, Anthropic, and Google)
  645. - `--tls-skip-verify`: Skip TLS certificate verification (WARNING: insecure, use only for self-signed certificates)
  646. - `--config string`: Config file location (default is $HOME/.mcphost.yml)
  647. - `--system-prompt string`: system-prompt file location
  648. - `--debug`: Enable debug logging
  649. - `--max-steps int`: Maximum number of agent steps (0 for unlimited, default: 0)
  650. - `-m, --model string`: Model to use (format: provider/model) (default "anthropic/claude-sonnet-4-5-20250929")
  651. - `-p, --prompt string`: **Run in non-interactive mode with the given prompt**
  652. - `--quiet`: **Suppress all output except the AI response (only works with --prompt)**
  653. - `--compact`: **Enable compact output mode without fancy styling (ideal for scripting and automation)**
  654. - `--stream`: Enable streaming responses (default: true, use `--stream=false` to disable)
  655. ### Authentication Subcommands
  656. - `mcphost auth login anthropic`: Authenticate with Anthropic using OAuth (alternative to API keys)
  657. - `mcphost auth logout anthropic`: Remove stored OAuth credentials
  658. - `mcphost auth status`: Show authentication status
  659. **Note**: OAuth credentials (when present) take precedence over API keys from environment variables and `--provider-api-key` flags.
  660. #### Model Generation Parameters
  661. - `--max-tokens int`: Maximum number of tokens in the response (default: 4096)
  662. - `--temperature float32`: Controls randomness in responses (0.0-1.0, default: 0.7)
  663. - `--top-p float32`: Controls diversity via nucleus sampling (0.0-1.0, default: 0.95)
  664. - `--top-k int32`: Controls diversity by limiting top K tokens to sample from (default: 40)
  665. - `--stop-sequences strings`: Custom stop sequences (comma-separated)
  666. ### Configuration File Support
  667. All command-line flags can be configured via the config file. MCPHost will look for configuration in this order:
  668. 1. `~/.mcphost.yml` or `~/.mcphost.json` (preferred)
  669. 2. `~/.mcp.yml` or `~/.mcp.json` (backwards compatibility)
  670. Example config file (`~/.mcphost.yml`):
  671. ```yaml
  672. # MCP Servers - New Simplified Format
  673. mcpServers:
  674. filesystem-local:
  675. type: "local"
  676. command: ["npx", "@modelcontextprotocol/server-filesystem", "/path/to/files"]
  677. environment:
  678. DEBUG: "true"
  679. filesystem-builtin:
  680. type: "builtin"
  681. name: "fs"
  682. options:
  683. allowed_directories: ["/tmp", "/home/user/documents"]
  684. websearch:
  685. type: "remote"
  686. url: "https://api.example.com/mcp"
  687. # Application settings
  688. model: "anthropic/claude-sonnet-4-5-20250929"
  689. max-steps: 20
  690. debug: false
  691. system-prompt: "/path/to/system-prompt.txt"
  692. # Model generation parameters
  693. max-tokens: 4096
  694. temperature: 0.7
  695. top-p: 0.95
  696. top-k: 40
  697. stop-sequences: ["Human:", "Assistant:"]
  698. # Streaming configuration
  699. stream: false # Disable streaming (default: true)
  700. # API Configuration
  701. provider-api-key: "your-api-key" # For OpenAI, Anthropic, or Google
  702. provider-url: "https://api.openai.com/v1" # Custom base URL
  703. tls-skip-verify: false # Skip TLS certificate verification (default: false)
  704. ```
  705. **Note**: Command-line flags take precedence over config file values.
  706. ### Interactive Commands
  707. While chatting, you can use:
  708. - `/help`: Show available commands
  709. - `/tools`: List all available tools
  710. - `/servers`: List configured MCP servers
  711. - `/history`: Display conversation history
  712. - `/quit`: Exit the application
  713. - `Ctrl+C`: Exit at any time
  714. ### Authentication Commands
  715. Optional OAuth authentication for Anthropic (alternative to API keys):
  716. - `mcphost auth login anthropic`: Authenticate using OAuth
  717. - `mcphost auth logout anthropic`: Remove stored OAuth credentials
  718. - `mcphost auth status`: Show authentication status
  719. ### Global Flags
  720. - `--config`: Specify custom config file location
  721. ## Automation & Scripting 🤖
  722. MCPHost's non-interactive mode makes it perfect for automation, scripting, and integration with other tools.
  723. ### Use Cases
  724. #### Shell Scripts
  725. ```bash
  726. #!/bin/bash
  727. # Get weather and save to file
  728. mcphost -p "What's the weather in New York?" --quiet > weather.txt
  729. # Process files with AI
  730. for file in *.txt; do
  731. summary=$(mcphost -p "Summarize this file: $(cat $file)" --quiet)
  732. echo "$file: $summary" >> summaries.txt
  733. done
  734. ```
  735. #### CI/CD Integration
  736. ```bash
  737. # Code review automation
  738. DIFF=$(git diff HEAD~1)
  739. mcphost -p "Review this code diff and suggest improvements: $DIFF" --quiet
  740. # Generate release notes
  741. COMMITS=$(git log --oneline HEAD~10..HEAD)
  742. mcphost -p "Generate release notes from these commits: $COMMITS" --quiet
  743. ```
  744. #### Data Processing
  745. ```bash
  746. # Process CSV data
  747. mcphost -p "Analyze this CSV data and provide insights: $(cat data.csv)" --quiet
  748. # Generate reports
  749. mcphost -p "Create a summary report from this JSON: $(cat metrics.json)" --quiet
  750. ```
  751. #### API Integration
  752. ```bash
  753. # Use as a microservice
  754. curl -X POST http://localhost:8080/process \
  755. -d "$(mcphost -p 'Generate a UUID' --quiet)"
  756. ```
  757. ### Tips for Scripting
  758. - Use `--quiet` flag to get clean output suitable for parsing (only AI response, no UI)
  759. - Use `--compact` flag for simplified output without fancy styling (when you want to see UI elements)
  760. - Note: `--compact` and `--quiet` are mutually exclusive - `--compact` has no effect with `--quiet`
  761. - **Use environment variables for sensitive data** like API keys instead of hardcoding them
  762. - **Use `${env://VAR}` syntax** in config files and scripts for environment variable substitution
  763. - Combine with standard Unix tools (`grep`, `awk`, `sed`, etc.)
  764. - Set appropriate timeouts for long-running operations
  765. - Handle errors appropriately in your scripts
  766. - Use environment variables for API keys in production
  767. #### Environment Variable Best Practices
  768. ```bash
  769. # Set sensitive variables in environment
  770. export GITHUB_TOKEN="ghp_your_token_here"
  771. export OPENAI_API_KEY="your_openai_key"
  772. export DATABASE_URL="postgresql://user:pass@localhost/db"
  773. # Use in config files
  774. mcpServers:
  775. github:
  776. environment:
  777. GITHUB_TOKEN: "${env://GITHUB_TOKEN}"
  778. DEBUG: "${env://DEBUG:-false}"
  779. # Use in scripts
  780. mcphost script my-script.sh --args:username alice
  781. ```
  782. ## MCP Server Compatibility 🔌
  783. MCPHost can work with any MCP-compliant server. For examples and reference implementations, see the [MCP Servers Repository](https://github.com/modelcontextprotocol/servers).
  784. ## Contributing 🤝
  785. Contributions are welcome! Feel free to:
  786. - Submit bug reports or feature requests through issues
  787. - Create pull requests for improvements
  788. - Share your custom MCP servers
  789. - Improve documentation
  790. Please ensure your contributions follow good coding practices and include appropriate tests.
  791. ## License 📄
  792. This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
  793. ## Acknowledgments 🙏
  794. - Thanks to the Anthropic team for Claude and the MCP specification
  795. - Thanks to the Ollama team for their local LLM runtime
  796. - Thanks to all contributors who have helped improve this tool

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.