Compare commits

...

3 commits

Author SHA1 Message Date
Ben
ea31ee97a2 Add comprehensive STATUS.md documenting current state
- Documents completed setup (config, documentation, git)
- Lists what's working vs. not implemented
- Identifies critical missing components
- Provides prioritized next steps
- Notes known issues and technical debt
- Sets clear success criteria for production readiness
- Estimates 2-3 weeks to MVP with high-priority tools
2025-11-07 12:29:15 -04:00
Ben
f69902bd33 Add Claude Desktop configuration script
- Created update_claude_config.py for safe config updates
- Automatically reads .env for API keys
- Creates backup before modifying config
- Validates paths and provides clear feedback
- Successfully configured zen-marketing MCP server in ~/.claude.json
2025-11-07 12:20:44 -04:00
Ben
122797d325 Update CLAUDE.md with improved /init format
- Restructured to follow /init specifications for Claude Code
- Added clear command reference for setup and development
- Documented architecture patterns (tool system, providers, conversation continuity)
- Explained schema generation and file processing systems
- Removed planning/roadmap content (belongs in PLAN.md)
- Added practical debugging tips and implementation patterns
- Focused on non-obvious architecture insights
2025-11-07 12:17:26 -04:00
3 changed files with 694 additions and 447 deletions

711
CLAUDE.md
View file

@ -1,84 +1,66 @@
# Claude Development Guide for Zen-Marketing MCP Server # CLAUDE.md
This file contains essential commands and workflows for developing the Zen-Marketing MCP Server - a specialized marketing-focused fork of Zen MCP Server. This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Context ## Project Overview
**What is Zen-Marketing?** Zen-Marketing is an MCP server for Claude Desktop providing AI-powered marketing tools. It's a fork of Zen MCP Server, specialized for marketing workflows rather than software development.
A Claude Desktop MCP server providing AI-powered marketing tools focused on:
- Content variation generation for A/B testing
- Cross-platform content adaptation
- Writing style enforcement
- SEO optimization for WordPress
- Guest content editing with voice preservation
- Technical fact verification
- Internal linking strategy
- Multi-channel campaign planning
**Target User:** Solo marketing professionals managing technical B2B content, particularly in industries like HVAC, SaaS, and technical education. **Key distinction:** This server generates content variations, enforces writing styles, and optimizes for platforms (LinkedIn, newsletters, WordPress) - not code review or debugging.
**Key Difference from Zen Code:** This is for marketing/content work, not software development. Tools generate content variations, enforce writing styles, and optimize for platforms like LinkedIn, newsletters, and WordPress - not code review or debugging. **Target user:** Solo marketing professionals managing technical B2B content (HVAC, SaaS, technical education).
## Quick Reference Commands ## Essential Commands
### Initial Setup ### Setup and Running
```bash ```bash
# Navigate to project directory # Initial setup
cd ~/mcp/zen-marketing ./run-server.sh
# Copy core files from zen-mcp-server (if starting fresh) # Manual setup
# We'll do this in the new session
# Create virtual environment
python3 -m venv .venv python3 -m venv .venv
source .venv/bin/activate source .venv/bin/activate
# Install dependencies (once requirements.txt is created)
pip install -r requirements.txt pip install -r requirements.txt
# Create .env file
cp .env.example .env cp .env.example .env
# Edit .env with your API keys # Edit .env with API keys
```
### Development Workflow # Run server
```bash
# Activate environment
source .venv/bin/activate
# Run code quality checks (once implemented)
./code_quality_checks.sh
# Run server locally for testing
python server.py python server.py
# View logs # Run with debug logging
LOG_LEVEL=DEBUG python server.py
```
### Testing and Development
```bash
# Watch logs during development
tail -f logs/mcp_server.log tail -f logs/mcp_server.log
# Run tests # Filter logs for specific tool
python -m pytest tests/ -v tail -f logs/mcp_server.log | grep -E "(TOOL_CALL|ERROR|contentvariant)"
# Test with Claude Desktop after changes
# Restart Claude Desktop to reload MCP server configuration
``` ```
### Claude Desktop Configuration ### Claude Desktop Configuration
Add to `~/.claude.json`: Configuration file: `~/.claude.json` or `~/Library/Application Support/Claude/claude_desktop_config.json`
```json ```json
{ {
"mcpServers": { "mcpServers": {
"zen-marketing": { "zen-marketing": {
"command": "/home/ben/mcp/zen-marketing/.venv/bin/python", "command": "/Users/ben/dev/mcp/zen-marketing/.venv/bin/python",
"args": ["/home/ben/mcp/zen-marketing/server.py"], "args": ["/Users/ben/dev/mcp/zen-marketing/server.py"],
"env": { "env": {
"OPENROUTER_API_KEY": "your-openrouter-key", "GEMINI_API_KEY": "your-key",
"GEMINI_API_KEY": "your-gemini-key", "DEFAULT_MODEL": "google/gemini-2.5-pro-latest",
"DEFAULT_MODEL": "gemini-2.5-pro", "FAST_MODEL": "google/gemini-2.5-flash-preview-09-2025",
"FAST_MODEL": "gemini-flash", "CREATIVE_MODEL": "minimax/minimax-m2",
"CREATIVE_MODEL": "minimax-m2",
"ENABLE_WEB_SEARCH": "true", "ENABLE_WEB_SEARCH": "true",
"DISABLED_TOOLS": "",
"LOG_LEVEL": "INFO" "LOG_LEVEL": "INFO"
} }
} }
@ -86,481 +68,316 @@ Add to `~/.claude.json`:
} }
``` ```
**After modifying config:** Restart Claude Desktop for changes to take effect. **Critical:** After modifying configuration, restart Claude Desktop completely for changes to take effect.
## Tool Development Guidelines ## Architecture Overview
### Tool Categories ### Tool System Design
**Simple Tools** (single-shot, fast response): The codebase uses a two-tier tool architecture inherited from Zen MCP Server:
- Inherit from `SimpleTool` base class
- Focus on speed and iteration
- Examples: `contentvariant`, `platformadapt`, `subjectlines`, `factcheck`
- Use fast models (gemini-flash) when possible
**Workflow Tools** (multi-step processes): 1. **Simple Tools** (`tools/simple/base.py`): Single-shot request/response tools for fast iteration
- Inherit from `WorkflowTool` base class - Example: `contentvariant` - generates 5-25 variations in one call
- Systematic step-by-step workflows - Use `ToolModelCategory.FAST_RESPONSE` for quick operations
- Track progress, confidence, findings - Inherit from `SimpleTool` base class
- Examples: `styleguide`, `seooptimize`, `guestedit`, `linkstrategy`
### Temperature Guidelines for Marketing Tools 2. **Workflow Tools** (`tools/workflow/base.py`): Multi-step systematic processes
- Track `step_number`, `total_steps`, `next_step_required`
- Maintain `findings` and `confidence` across steps
- Example: `styleguide` - detect → flag → rewrite → validate
- Use `ToolModelCategory.DEEP_THINKING` for complex analysis
- **High (0.7-0.8)**: Content variation, creative adaptation ### Provider System
- **Medium (0.5-0.6)**: Balanced tasks, campaign planning
- **Low (0.3-0.4)**: Analytical work, SEO optimization
- **Very Low (0.2)**: Fact-checking, technical verification
### Model Selection Strategy Model providers are managed through a registry pattern (`providers/registry.py`):
**Gemini 2.5 Pro** (`gemini-2.5-pro`): - **Priority order:** GOOGLE (Gemini) → OPENAI → XAI → DIAL → CUSTOM → OPENROUTER
- Analytical and strategic work - **Lazy initialization:** Providers are only instantiated when first needed
- SEO optimization - **Model categories:** Tools request `FAST_RESPONSE` or `DEEP_THINKING`, registry selects best available model
- Guest editing - **Fallback chain:** If primary provider fails, falls back to next in priority order
- Internal linking analysis
- Voice analysis
- Campaign planning
- Fact-checking
**Gemini Flash** (`gemini-flash`): Key providers:
- Fast bulk generation - `gemini.py` - Google Gemini API (analytical work)
- Subject line creation - `openai_compatible.py` - OpenAI and compatible APIs
- Quick variations - `openrouter.py` - Fallback for cloud models
- Cost-effective iterations - `custom.py` - Self-hosted models
**Minimax M2** (`minimax-m2`): ### Conversation Continuity
- Creative content generation
- Platform adaptation
- Content repurposing
- Marketing copy variations
### System Prompt Best Practices Every tool supports `continuation_id` for stateful conversations:
Marketing tool prompts should: 1. First call returns a `continuation_id` in response
1. **Specify output format clearly** (JSON, markdown, numbered list) 2. Subsequent calls include this ID to preserve context
2. **Include platform constraints** (character limits, formatting rules) 3. Stored in-memory with 6-hour expiration (configurable)
3. **Emphasize preservation** (voice, expertise, technical accuracy) 4. Managed by `utils/conversation_memory.py`
4. **Request rationale** (why certain variations work, what to test)
5. **Avoid code terminology** (use "content" not "implementation")
Example prompt structure: This allows follow-up interactions like:
```python - "Now check if this new draft matches the voice" (after voice analysis)
CONTENTVARIANT_PROMPT = """ - "Generate 10 more variations with different angles" (after initial generation)
You are a marketing content strategist specializing in A/B testing and variation generation.
TASK: Generate multiple variations of marketing content for testing different approaches. ### File Processing
OUTPUT FORMAT: Tools automatically handle file inputs (`utils/file_utils.py`):
Return variations as numbered list, each with: - Directory expansion (recursively processes all files in directory)
1. The variation text - Deduplication (removes duplicate file paths)
2. The testing angle (what makes it different) - Image support (screenshots, brand assets via `utils/image_utils.py`)
3. Predicted audience response - Path resolution (converts relative to absolute paths)
CONSTRAINTS: Files are included in model context, so tools can reference brand guidelines, content samples, etc.
- Maintain core message across variations
- Respect platform character limits if specified
- Preserve brand voice characteristics
- Generate genuinely different approaches, not just word swaps
VARIATION TYPES: ### Schema Generation
- Hook variations: Different opening angles
- Length variations: Short, medium, long
- Tone variations: Professional, conversational, urgent
- Structure variations: Question, statement, story
- CTA variations: Different calls-to-action
"""
```
## Implementation Phases Tools use a builder pattern for MCP schemas (`tools/shared/schema_builders.py`):
- `SchemaBuilder` - Generates MCP tool schemas from Pydantic models
- `WorkflowSchemaBuilder` - Specialized for workflow tools with step tracking
- Automatic field type conversion (Pydantic → JSON Schema)
- Shared field definitions (files, images, continuation_id, model, temperature)
### Phase 1: Foundation ✓ (You Are Here) ## Tool Implementation Pattern
- [x] Create project directory
- [x] Write implementation plan (PLAN.md)
- [x] Create development guide (CLAUDE.md)
- [ ] Copy core architecture from zen-mcp-server
- [ ] Configure minimax provider
- [ ] Remove code-specific tools
- [ ] Test basic chat functionality
### Phase 2: Simple Tools (Priority: High) ### Creating a Simple Tool
Implementation order based on real-world usage:
1. **`contentvariant`** - Most frequently used (subject lines, social posts)
2. **`subjectlines`** - Specific workflow mentioned in project memories
3. **`platformadapt`** - Multi-channel content distribution
4. **`factcheck`** - Technical accuracy verification
### Phase 3: Workflow Tools (Priority: Medium)
5. **`styleguide`** - Writing rule enforcement (no em-dashes, etc.)
6. **`seooptimize`** - WordPress SEO optimization
7. **`guestedit`** - Guest content editing workflow
8. **`linkstrategy`** - Internal linking and cross-platform integration
### Phase 4: Advanced Features (Priority: Lower)
9. **`voiceanalysis`** - Voice extraction and consistency checking
10. **`campaignmap`** - Multi-touch campaign planning
## Tool Implementation Checklist
For each new tool:
**Code Files:**
- [ ] Create tool file in `tools/` (e.g., `tools/contentvariant.py`)
- [ ] Create system prompt in `systemprompts/` (e.g., `systemprompts/contentvariant_prompt.py`)
- [ ] Create test file in `tests/` (e.g., `tests/test_contentvariant.py`)
- [ ] Register tool in `server.py`
**Tool Class Requirements:**
- [ ] Inherit from `SimpleTool` or `WorkflowTool`
- [ ] Implement `get_name()` - tool name
- [ ] Implement `get_description()` - what it does
- [ ] Implement `get_system_prompt()` - behavior instructions
- [ ] Implement `get_default_temperature()` - creativity level
- [ ] Implement `get_model_category()` - FAST_RESPONSE or DEEP_THINKING
- [ ] Implement `get_request_model()` - Pydantic request schema
- [ ] Implement `get_input_schema()` - MCP tool schema
- [ ] Implement request/response formatting hooks
**Testing:**
- [ ] Unit tests for request validation
- [ ] Unit tests for response formatting
- [ ] Integration test with real model (optional)
- [ ] Add to quality checks script
**Documentation:**
- [ ] Add tool to README.md
- [ ] Create examples in docs/tools/
- [ ] Update PLAN.md progress
## Common Development Tasks
### Adding a New Simple Tool
```python ```python
# tools/mynewtool.py # tools/mymarketingtool.py
from typing import Optional
from pydantic import Field from pydantic import Field
from tools.shared.base_models import ToolRequest from tools.shared.base_models import ToolRequest
from .simple.base import SimpleTool from tools.simple.base import SimpleTool
from systemprompts import MYNEWTOOL_PROMPT from tools.models import ToolModelCategory
from config import TEMPERATURE_BALANCED from systemprompts import MYMARKETINGTOOL_PROMPT
from config import TEMPERATURE_CREATIVE
class MyNewToolRequest(ToolRequest): class MyMarketingToolRequest(ToolRequest):
"""Request model for MyNewTool""" content: str = Field(..., description="Content to process")
prompt: str = Field(..., description="What you want to accomplish") platform: str = Field(default="linkedin", description="Target platform")
files: Optional[list[str]] = Field(default_factory=list)
class MyNewTool(SimpleTool): class MyMarketingTool(SimpleTool):
def get_name(self) -> str: def get_name(self) -> str:
return "mynewtool" return "mymarketingtool"
def get_description(self) -> str: def get_description(self) -> str:
return "Brief description of what this tool does" return "Brief description shown in Claude Desktop"
def get_system_prompt(self) -> str: def get_system_prompt(self) -> str:
return MYNEWTOOL_PROMPT return MYMARKETINGTOOL_PROMPT
def get_default_temperature(self) -> float: def get_default_temperature(self) -> float:
return TEMPERATURE_BALANCED return TEMPERATURE_CREATIVE
def get_model_category(self) -> "ToolModelCategory": def get_model_category(self) -> ToolModelCategory:
from tools.models import ToolModelCategory
return ToolModelCategory.FAST_RESPONSE return ToolModelCategory.FAST_RESPONSE
def get_request_model(self): def get_request_model(self):
return MyNewToolRequest return MyMarketingToolRequest
``` ```
### Adding a New Workflow Tool ### Registering a Tool
In `server.py`, add to the `_initialize_tools()` method:
```python ```python
# tools/mynewworkflow.py from tools.mymarketingtool import MyMarketingTool
from typing import Optional
from pydantic import Field
from tools.shared.base_models import WorkflowRequest
from .workflow.base import WorkflowTool
from systemprompts import MYNEWWORKFLOW_PROMPT
class MyNewWorkflowRequest(WorkflowRequest): def _initialize_tools(self) -> list[BaseTool]:
"""Request model for workflow tool""" tools = [
step: str = Field(description="Current step content") ChatTool(),
step_number: int = Field(ge=1) ContentVariantTool(),
total_steps: int = Field(ge=1) MyMarketingTool(), # Add here
next_step_required: bool # ... other tools
findings: str = Field(description="What was discovered") ]
# Add workflow-specific fields return tools
class MyNewWorkflow(WorkflowTool):
# Implementation similar to Simple Tool
# but with workflow-specific logic
``` ```
### Testing a Tool Manually ### System Prompt Structure
```bash System prompts live in `systemprompts/`:
# Start server with debug logging
LOG_LEVEL=DEBUG python server.py
# In another terminal, watch logs ```python
tail -f logs/mcp_server.log | grep -E "(TOOL_CALL|ERROR|MyNewTool)" # systemprompts/mymarketingtool_prompt.py
MYMARKETINGTOOL_PROMPT = """
You are a marketing content specialist.
# In Claude Desktop, test: TASK: [Clear description of what this tool does]
# "Use zen-marketing to generate 10 subject lines about HVAC maintenance"
OUTPUT FORMAT:
[Specify exact format - JSON, markdown, numbered list, etc.]
CONSTRAINTS:
- Character limits for platform
- Preserve brand voice
- Technical accuracy required
PROCESS:
1. Step one
2. Step two
3. Final output
"""
``` ```
**Import in systemprompts/__init__.py:**
```python
from .mymarketingtool_prompt import MYMARKETINGTOOL_PROMPT
```
## Temperature Configurations
Defined in `config.py` for different content types:
- `TEMPERATURE_PRECISION` (0.2) - Fact-checking, technical verification
- `TEMPERATURE_ANALYTICAL` (0.3) - Style enforcement, SEO optimization
- `TEMPERATURE_BALANCED` (0.5) - Strategic planning, guest editing
- `TEMPERATURE_CREATIVE` (0.7) - Platform adaptation
- `TEMPERATURE_HIGHLY_CREATIVE` (0.8) - Content variation, subject lines
Choose based on whether tool needs creativity (variations) or precision (fact-checking).
## Platform Character Limits
Defined in `config.py` as `PLATFORM_LIMITS`:
```python
PLATFORM_LIMITS = {
"twitter": 280,
"bluesky": 300,
"linkedin": 3000,
"linkedin_optimal": 1300,
"instagram": 2200,
"facebook": 500,
"email_subject": 60,
"email_preview": 100,
"meta_description": 156,
"page_title": 60,
}
```
Tools reference these when generating platform-specific content.
## Model Selection Strategy
Tools specify category, not specific model:
- **FAST_RESPONSE** → Uses `FAST_MODEL` from config (default: gemini-flash)
- **DEEP_THINKING** → Uses `DEFAULT_MODEL` from config (default: gemini-2.5-pro)
Users can override:
1. Via `model` parameter in tool request
2. Via environment variables (`DEFAULT_MODEL`, `FAST_MODEL`, `CREATIVE_MODEL`)
**Default models:**
- Analytical work: `google/gemini-2.5-pro-latest`
- Fast generation: `google/gemini-2.5-flash-preview-09-2025`
- Creative content: `minimax/minimax-m2`
## Debugging Tips
### Tool Not Appearing
1. Check tool is registered in `server.py`
2. Verify not in `DISABLED_TOOLS` env var
3. Check logs: `tail -f logs/mcp_server.log`
4. Restart Claude Desktop after config changes
### Model Errors
1. Verify API key in `.env` file
2. Check provider supports requested model
3. Look for provider errors in logs
4. Test with explicit model name override
### Response Issues
1. Check system prompt specifies output format clearly
2. Verify response doesn't exceed token limits
3. Review logs for truncation warnings
4. Test with simpler input first
### Conversation Context Lost
1. Verify `continuation_id` passed correctly
2. Check conversation hasn't expired (6 hours default)
3. Look for memory errors in logs: `grep "continuation_id" logs/mcp_server.log`
## Project Structure ## Project Structure
``` Key directories:
zen-marketing/
├── server.py # Main MCP server entry point
├── config.py # Configuration constants
├── PLAN.md # Implementation plan (this doc)
├── CLAUDE.md # Development guide
├── README.md # User-facing documentation
├── requirements.txt # Python dependencies
├── .env.example # Environment variable template
├── .env # Local config (gitignored)
├── run-server.sh # Setup and run script
├── code_quality_checks.sh # Linting and testing
├── tools/ # Tool implementations
│ ├── __init__.py
│ ├── contentvariant.py # Bulk variation generator
│ ├── platformadapt.py # Cross-platform adapter
│ ├── subjectlines.py # Email subject line generator
│ ├── styleguide.py # Writing style enforcer
│ ├── seooptimize.py # SEO optimizer
│ ├── guestedit.py # Guest content editor
│ ├── linkstrategy.py # Internal linking strategist
│ ├── factcheck.py # Technical fact checker
│ ├── voiceanalysis.py # Voice extractor/validator
│ ├── campaignmap.py # Campaign planner
│ ├── chat.py # General chat (from zen)
│ ├── thinkdeep.py # Deep thinking (from zen)
│ ├── planner.py # Planning (from zen)
│ ├── models.py # Shared models
│ ├── simple/ # Simple tool base classes
│ │ └── base.py
│ ├── workflow/ # Workflow tool base classes
│ │ └── base.py
│ └── shared/ # Shared utilities
│ └── base_models.py
├── providers/ # AI provider implementations
│ ├── __init__.py
│ ├── base.py # Base provider interface
│ ├── gemini.py # Google Gemini
│ ├── minimax.py # Minimax (NEW)
│ ├── openrouter.py # OpenRouter fallback
│ ├── registry.py # Provider registry
│ └── shared/
├── systemprompts/ # System prompts for tools
│ ├── __init__.py
│ ├── contentvariant_prompt.py
│ ├── platformadapt_prompt.py
│ ├── subjectlines_prompt.py
│ ├── styleguide_prompt.py
│ ├── seooptimize_prompt.py
│ ├── guestedit_prompt.py
│ ├── linkstrategy_prompt.py
│ ├── factcheck_prompt.py
│ ├── voiceanalysis_prompt.py
│ ├── campaignmap_prompt.py
│ ├── chat_prompt.py # From zen
│ ├── thinkdeep_prompt.py # From zen
│ └── planner_prompt.py # From zen
├── utils/ # Utility functions
│ ├── conversation_memory.py # Conversation continuity
│ ├── file_utils.py # File handling
│ └── web_search.py # Web search integration
├── tests/ # Test suite
│ ├── __init__.py
│ ├── test_contentvariant.py
│ ├── test_platformadapt.py
│ ├── test_subjectlines.py
│ └── ...
├── logs/ # Log files (gitignored)
│ ├── mcp_server.log
│ └── mcp_activity.log
└── docs/ # Documentation
├── getting-started.md
├── tools/
│ ├── contentvariant.md
│ ├── platformadapt.md
│ └── ...
└── examples/
└── marketing-workflows.md
```
## Key Concepts from Zen Architecture - `server.py` - MCP server implementation, tool registration
- `config.py` - Configuration constants, temperature defaults, platform limits
- `tools/` - Tool implementations (simple/ and workflow/ subdirs)
- `providers/` - AI model provider implementations
- `systemprompts/` - System prompts for each tool
- `utils/` - Shared utilities (file handling, conversation memory, image processing)
- `logs/` - Server logs (gitignored)
### Conversation Continuity ## Marketing-Specific Context
Every tool supports `continuation_id` to maintain context across interactions:
```python ### Writing Style Rules
# First call
result1 = await tool.execute({
"prompt": "Analyze this brand voice",
"files": ["brand_samples/post1.txt", "brand_samples/post2.txt"]
})
# Returns: continuation_id: "abc123"
# Follow-up call (remembers previous context) From project memories, tools should enforce:
result2 = await tool.execute({
"prompt": "Now check if this new draft matches the voice",
"files": ["new_draft.txt"],
"continuation_id": "abc123" # Preserves context
})
```
### File Handling
Tools automatically:
- Expand directories to individual files
- Deduplicate file lists
- Handle absolute paths
- Process images (screenshots, brand assets)
### Web Search Integration
Tools can request Claude to perform web searches:
```python
# In system prompt:
"If you need current information about [topic], request a web search from Claude."
# Claude will then use WebSearch tool and provide results
```
### Multi-Model Orchestration
Tools specify model category, server selects best available:
- `FAST_RESPONSE` → gemini-flash or equivalent
- `DEEP_THINKING` → gemini-2.5-pro or equivalent
- User can override with `model` parameter
## Debugging Common Issues
### Tool Not Appearing in Claude Desktop
1. Check `server.py` registers the tool
2. Verify tool is not in `DISABLED_TOOLS` env var
3. Restart Claude Desktop after config changes
4. Check logs: `tail -f logs/mcp_server.log`
### Model Selection Issues
1. Verify API keys in `.env`
2. Check provider registration in `providers/registry.py`
3. Test with explicit model name: `"model": "gemini-2.5-pro"`
4. Check logs for provider errors
### Response Formatting Issues
1. Validate system prompt specifies output format
2. Check response doesn't exceed token limits
3. Test with simpler input first
4. Review logs for truncation warnings
### Conversation Continuity Not Working
1. Verify `continuation_id` is being passed correctly
2. Check conversation hasn't expired (default 6 hours)
3. Validate conversation memory storage
4. Review logs: `grep "continuation_id" logs/mcp_server.log`
## Code Quality Standards
Before committing:
```bash
# Run all quality checks
./code_quality_checks.sh
# Manual checks:
ruff check . --fix # Linting
black . # Formatting
isort . # Import sorting
pytest tests/ -v # Run tests
```
## Marketing-Specific Considerations
### Character Limits by Platform
Tools should be aware of:
- **Twitter/Bluesky**: 280 characters
- **LinkedIn**: 3000 chars (1300 optimal)
- **Instagram**: 2200 characters
- **Facebook**: No hard limit (500 chars optimal)
- **Email subject**: 60 characters optimal
- **Email preview**: 90-100 characters
- **Meta description**: 156 characters
- **Page title**: 60 characters
### Writing Style Rules from Project Memories
- No em-dashes (use periods or semicolons) - No em-dashes (use periods or semicolons)
- No "This isn't X, it's Y" constructions - No "This isn't X, it's Y" constructions
- Direct affirmative statements over negations - Direct affirmative statements over negations
- Semantic variety in paragraph openings - Semantic variety in paragraph openings
- Concrete metrics over abstract claims - Concrete metrics over abstract claims
- Technical accuracy preserved
- Author voice maintained
### Testing Angles for Variations ### Testing Angles for Variations
Common psychological angles for A/B testing:
- Technical curiosity - Technical curiosity
- Contrarian/provocative - Contrarian/provocative
- Knowledge gap emphasis - Knowledge gap emphasis
- Urgency/timeliness - Urgency/timeliness
- Insider knowledge positioning - Insider knowledge
- Problem-solution framing - Problem-solution framing
- Before-after transformation - Before-after transformation
- Social proof/credibility - Social proof/credibility
- FOMO (fear of missing out) - FOMO (fear of missing out)
- Educational value - Educational value
## Next Session Goals ### Platform Best Practices
When you start the new session in `~/mcp/zen-marketing/`: - **LinkedIn**: 1300 chars optimal (3000 max), professional tone
- **Twitter/Bluesky**: 280 chars, conversational, high engagement hooks
- **Email subject**: 60 chars, action-oriented, clear value prop
- **Instagram**: 2200 chars, visual storytelling, emojis appropriate
- **Blog/WordPress**: SEO-optimized titles (<60 chars), meta descriptions (<156 chars)
1. **Copy Core Files from Zen** ## Key Differences from Zen MCP Server
- Copy base architecture preserving git history
- Remove code-specific tools
- Update imports and references
2. **Configure Minimax Provider** 1. **Removed tools:** debug, codereview, refactor, testgen, secaudit, docgen, tracer, precommit
- Add minimax support to providers/ 2. **Added tools:** contentvariant, platformadapt, subjectlines, styleguide, seooptimize, guestedit, linkstrategy, factcheck
- Register in provider registry 3. **Kept tools:** chat, thinkdeep, planner (useful for marketing strategy)
- Test basic model calls 4. **New focus:** Content variation, platform adaptation, voice preservation
5. **Model preference:** Minimax for creative generation, Gemini for analytical work
3. **Implement First Simple Tool** ## Current Implementation Status
- Start with `contentvariant` (highest priority)
- Create tool, system prompt, and tests
- Test end-to-end with Claude Desktop
4. **Validate Architecture** **Completed:**
- Ensure conversation continuity works - [x] Core architecture from Zen MCP Server
- Verify file handling - [x] Provider system (Gemini, OpenAI, OpenRouter)
- Test web search integration - [x] Tool base classes (SimpleTool, WorkflowTool)
- [x] Conversation continuity system
- [x] File processing utilities
- [x] Basic tools: chat, contentvariant, listmodels, version
## Questions to Consider **In Progress:**
- [ ] Additional simple tools (platformadapt, subjectlines, factcheck)
- [ ] Workflow tools (styleguide, seooptimize, guestedit, linkstrategy)
- [ ] Minimax provider configuration
- [ ] Advanced features (voiceanalysis, campaignmap)
Before implementing each tool: See PLAN.md for detailed implementation roadmap.
1. What real-world workflow does this solve? (Reference project memories)
2. What's the minimum viable version? ## Git Workflow
3. What can go wrong? (Character limits, API errors, invalid input)
4. How will users test variations? (Output format) **Commit signature:** Ben Reed `ben@tealmaker.com` (not Claude Code)
5. Does it need web search? (Current info, fact-checking)
6. What's the right temperature? (Creative vs analytical) **Commit frequency:** After reasonable amount of updates (not after every small change)
7. Simple or workflow tool? (Single-shot vs multi-step)
## Resources ## Resources
- **Zen MCP Server Repo**: Source for architecture and patterns - MCP Protocol: https://modelcontextprotocol.com
- **MCP Protocol Docs**: https://modelcontextprotocol.com - Zen MCP Server (parent project): https://github.com/BeehiveInnovations/zen-mcp-server
- **Claude Desktop Config**: `~/.claude.json` - Claude Desktop download: https://claude.ai/download
- **Project Memories**: See PLAN.md for user workflow examples - Project planning: See PLAN.md for tool designs and implementation phases
- **Platform Best Practices**: Research current 2025 guidelines - User documentation: See README.md for end-user features
---
**Ready to build?** Start the new session with:
```bash
cd ~/mcp/zen-marketing
# Then ask Claude to begin Phase 1 implementation
```

305
STATUS.md Normal file
View file

@ -0,0 +1,305 @@
# Zen-Marketing MCP Server - Current Status
**Last Updated:** 2025-11-07
**Phase:** Foundation Complete, Implementation Pending
**Version:** 0.1.0 (Initial Setup)
## Current State
### ✅ Completed
1. **Project Structure**
- Repository initialized with git
- Directory structure created
- Core architecture copied from Zen MCP Server
- Base classes for Simple and Workflow tools in place
2. **Configuration**
- `.env` file created with API keys:
- OpenRouter API key configured
- Gemini API key configured
- Claude Desktop configured at `~/.claude.json`:
- zen-marketing server registered
- Model configuration set (Gemini 2.5 Pro, Flash, Minimax M2)
- Web search enabled
- Configuration update script created (`update_claude_config.py`)
3. **Documentation**
- `CLAUDE.md` - Development guide for future Claude instances
- `PLAN.md` - Detailed implementation roadmap
- `README.md` - User-facing documentation
- `STATUS.md` - This file
4. **Git Setup**
- User configured (Ben / benreed1987@gmail.com)
- Initial commits made
- `.gitignore` properly configured
5. **Existing Tools (from Zen MCP Server base)**
- `chat` - General brainstorming
- `thinkdeep` - Deep analysis
- `planner` - Project planning
- `listmodels` - List available AI models
- `version` - Server version info
- Plus code-focused tools that need to be removed or adapted
### ⚠️ Important Notes
**The server is NOT production-ready yet.** While the infrastructure is in place, most marketing-specific tools have not been implemented.
**Current tools/__init__.py** shows imports for code-focused tools that need to be removed:
- `analyze`, `codereview`, `consensus`, `debug`, `docgen`, `precommit`, `refactor`, `secaudit`, `testgen`, `tracer`, `challenge`
These are inherited from Zen MCP Server and are not relevant for marketing workflows.
## What's Working
- ✅ Server can start (virtual environment configured)
- ✅ MCP protocol communication
- ✅ Provider system (Gemini, OpenRouter)
- ✅ Base tool architecture (SimpleTool, WorkflowTool)
- ✅ Conversation continuity system
- ✅ File processing utilities
- ✅ Basic tools: chat, listmodels, version
## What's NOT Working / Not Implemented
### Critical Missing Components
1. **Marketing Tools Not Implemented**
- `contentvariant` - Started but needs completion
- `platformadapt` - Not started
- `subjectlines` - Not started
- `factcheck` - Not started
- `styleguide` - Not started
- `seooptimize` - Not started
- `guestedit` - Not started
- `linkstrategy` - Not started
- `voiceanalysis` - Not started
- `campaignmap` - Not started
2. **Code Tools Need Removal**
- tools/__init__.py imports many code-focused tools
- server.py likely registers these tools
- System prompts for code tools should be removed
- Only keep: chat, thinkdeep, planner (useful for marketing)
3. **Provider Issues**
- Minimax provider may not be properly configured
- Need to verify Gemini provider works with new API key
- OpenRouter fallback needs testing
4. **System Prompts**
- Only 2 marketing-specific prompts exist:
- `contentvariant_prompt.py`
- `chat_prompt.py` (generic)
- Need 8+ marketing-focused system prompts
5. **Testing**
- No tests written yet
- Server hasn't been started/tested
- Tool functionality unverified
## Next Steps (Priority Order)
### Immediate (Next Session)
1. **Review and Update PLAN.md**
- Verify implementation roadmap
- Adjust priorities based on current state
- Identify any missing requirements
2. **Clean Up Tool Registry**
- Remove code-focused tools from tools/__init__.py
- Update server.py to only register relevant tools
- Remove unused system prompts
3. **Complete contentvariant Tool** (Highest Priority)
- Finish implementation
- Create comprehensive system prompt
- Test with real content
- This is the most requested feature from project memories
4. **Test Server Startup**
- Start server: `python server.py`
- Check logs for errors
- Verify MCP protocol working
- Test with Claude Desktop
### Phase 2: Simple Tools (Week 2)
5. **Implement subjectlines Tool**
- Create tool class
- Write system prompt for email subject generation
- Test psychological angles (curiosity, urgency, FOMO, etc.)
6. **Implement platformadapt Tool**
- Cross-platform content adaptation
- Platform-specific character limits
- Tone/format adjustments
7. **Implement factcheck Tool**
- Web search integration
- Technical claim verification
- Source citation
### Phase 3: Workflow Tools (Week 3-4)
8. **Implement styleguide Tool**
- Multi-step style enforcement
- Violation detection and rewriting
- Custom rule support
9. **Implement seooptimize Tool**
- WordPress-specific SEO workflow
- Title/meta generation
- Internal linking suggestions
10. **Implement guestedit Tool**
- Voice preservation workflow
- Educational enhancements
- Technical accuracy verification
11. **Implement linkstrategy Tool**
- Cross-platform content mapping
- Internal linking opportunities
- Content relationship analysis
### Phase 4: Advanced (Week 5+)
12. **Implement voiceanalysis Tool**
- Voice pattern extraction
- Consistency checking
- Voice profile generation
13. **Implement campaignmap Tool**
- Multi-touch campaign planning
- Content calendar generation
- Cross-promotion strategy
## Technical Debt
1. **Provider Configuration**
- Minimax provider needs implementation/testing
- May need alternative creative model if Minimax unavailable
2. **Error Handling**
- Need comprehensive error handling for marketing workflows
- User-friendly error messages
3. **Documentation**
- Need tool-specific documentation
- Usage examples for each tool
- Marketing workflow guides
4. **Testing**
- Unit tests for each tool
- Integration tests
- End-to-end workflow tests
## File Locations
```
/Users/ben/dev/mcp/zen-marketing/
├── server.py # Main MCP server
├── config.py # Configuration constants
├── .env # API keys (not in git)
├── requirements.txt # Python dependencies
├── update_claude_config.py # Claude Desktop config updater
├── CLAUDE.md # Development guide
├── PLAN.md # Implementation roadmap
├── README.md # User documentation
├── STATUS.md # This file
├── tools/ # Tool implementations
│ ├── __init__.py # Tool registry (needs cleanup)
│ ├── chat.py # ✅ Working
│ ├── contentvariant.py # ⚠️ Partial
│ ├── listmodels.py # ✅ Working
│ ├── version.py # ✅ Working
│ ├── simple/base.py # ✅ Base class
│ └── workflow/base.py # ✅ Base class
├── providers/ # AI provider implementations
│ ├── gemini.py # ✅ Should work
│ ├── openrouter.py # ✅ Should work
│ └── registry.py # ✅ Provider management
├── systemprompts/ # System prompts for tools
│ ├── contentvariant_prompt.py # ⚠️ Needs completion
│ └── chat_prompt.py # ✅ Generic prompt
└── utils/ # Shared utilities
├── file_utils.py # ✅ File handling
├── conversation_memory.py # ✅ Continuity
└── image_utils.py # ✅ Image processing
```
## Configuration Files
**Claude Desktop**: `~/.claude.json`
- Server: zen-marketing (registered)
- Backup: `~/.claude.json.backup`
**Environment**: `/Users/ben/dev/mcp/zen-marketing/.env`
- OpenRouter API Key: Configured
- Gemini API Key: Configured
- Models: gemini-2.5-pro, gemini-flash, minimax-m2
## Known Issues
1. **Server Untested**
- Haven't started server yet
- May have import errors due to tool cleanup needed
- Logs directory may not have write permissions
2. **Tool Registry Mismatch**
- tools/__init__.py imports code tools
- server.py may try to register non-existent marketing tools
- Will cause startup errors
3. **System Prompts Missing**
- Most marketing tools lack system prompts
- Will fail if called without prompts
4. **Provider Verification Needed**
- Gemini API key not tested
- Minimax provider may not exist
- Need fallback strategy
## Success Criteria (When Ready for Use)
- [ ] Server starts without errors
- [ ] contentvariant tool generates 10+ usable variations
- [ ] Character limits respected for all platforms
- [ ] Voice preservation works in guest editing
- [ ] SEO titles/descriptions pass WordPress validation
- [ ] Cross-platform content mapping accurate
- [ ] Fact-checking cites sources correctly
- [ ] Style guide catches and fixes violations
- [ ] Response time <10s for simple tools, <30s for workflows
## Resources
- **Zen MCP Server**: https://github.com/BeehiveInnovations/zen-mcp-server
- **MCP Protocol**: https://modelcontextprotocol.com
- **Gemini API**: https://ai.google.dev/
- **OpenRouter**: https://openrouter.ai/
## Session Notes
**2025-11-07 Session:**
- Created initial structure
- Configured environment and Claude Desktop
- Updated CLAUDE.md with architecture insights
- Identified that server is not production-ready
- Documented current state and next steps
**Next Session Goals:**
1. Review PLAN.md in detail
2. Clean up tool imports
3. Test server startup
4. Complete contentvariant tool
5. Begin implementing subjectlines tool
---
**Status**: 🟡 Foundation Complete, Implementation in Progress
**Blocker**: Need to implement marketing-specific tools before server is usable
**Estimated Time to MVP**: 2-3 weeks (with focus on high-priority tools)

125
update_claude_config.py Executable file
View file

@ -0,0 +1,125 @@
#!/usr/bin/env python3
"""
Script to safely add zen-marketing MCP server to Claude Desktop configuration.
"""
import json
import os
import shutil
from pathlib import Path
def update_claude_config():
"""Add zen-marketing server to Claude Desktop config"""
# Path to Claude config
config_path = Path.home() / ".claude.json"
if not config_path.exists():
print(f"Error: Config file not found at {config_path}")
return False
# Create backup
backup_path = config_path.with_suffix('.json.backup')
shutil.copy2(config_path, backup_path)
print(f"✓ Created backup: {backup_path}")
# Read current config
with open(config_path, 'r') as f:
config = json.load(f)
# Get MCP servers section
if 'mcpServers' not in config:
config['mcpServers'] = {}
# Get absolute paths
project_root = Path(__file__).parent.resolve()
venv_python = project_root / ".venv" / "bin" / "python"
server_script = project_root / "server.py"
# Verify paths exist
if not venv_python.exists():
print(f"Error: Python venv not found at {venv_python}")
print("Run ./run-server.sh first to create the virtual environment")
return False
if not server_script.exists():
print(f"Error: server.py not found at {server_script}")
return False
# Read OpenRouter key from .env
env_file = project_root / ".env"
openrouter_key = ""
gemini_key = ""
if env_file.exists():
with open(env_file, 'r') as f:
for line in f:
if line.startswith('OPENROUTER_API_KEY='):
openrouter_key = line.split('=', 1)[1].strip()
elif line.startswith('GEMINI_API_KEY='):
gemini_key = line.split('=', 1)[1].strip()
if not openrouter_key:
print("Warning: OPENROUTER_API_KEY not found in .env")
# Create zen-marketing server config
zen_marketing_config = {
"command": str(venv_python),
"args": [str(server_script)],
"env": {
"DEFAULT_MODEL": "google/gemini-2.5-pro-latest",
"FAST_MODEL": "google/gemini-2.5-flash-preview-09-2025",
"CREATIVE_MODEL": "minimax/minimax-m2",
"ENABLE_WEB_SEARCH": "true",
"LOG_LEVEL": "INFO"
}
}
# Add API keys if available
if openrouter_key:
zen_marketing_config["env"]["OPENROUTER_API_KEY"] = openrouter_key
if gemini_key:
zen_marketing_config["env"]["GEMINI_API_KEY"] = gemini_key
# Check if zen-marketing already exists
if 'zen-marketing' in config['mcpServers']:
print("\n⚠ zen-marketing server already configured")
response = input("Overwrite existing configuration? (y/N): ")
if response.lower() != 'y':
print("Cancelled.")
return False
# Add/update zen-marketing
config['mcpServers']['zen-marketing'] = zen_marketing_config
# Write updated config
with open(config_path, 'w') as f:
json.dump(config, f, indent=2)
print(f"\n✓ Added zen-marketing MCP server to {config_path}")
print(f"\nConfiguration:")
print(f" Command: {venv_python}")
print(f" Script: {server_script}")
print(f" Models:")
print(f" - DEFAULT: {zen_marketing_config['env']['DEFAULT_MODEL']}")
print(f" - FAST: {zen_marketing_config['env']['FAST_MODEL']}")
print(f" - CREATIVE: {zen_marketing_config['env']['CREATIVE_MODEL']}")
if openrouter_key:
print(f" OpenRouter API Key: {'*' * (len(openrouter_key) - 8)}{openrouter_key[-8:]}")
if gemini_key:
print(f" Gemini API Key: {'*' * (len(gemini_key) - 8)}{gemini_key[-8:]}")
print(f"\n⚠ IMPORTANT: Restart Claude Desktop for changes to take effect")
return True
if __name__ == "__main__":
try:
success = update_claude_config()
if not success:
exit(1)
except Exception as e:
print(f"Error: {e}")
import traceback
traceback.print_exc()
exit(1)