Repository files navigation

Code Agent

A Go-based CLI tool for interacting with Anthropic's Claude AI assistant. This tool provides an interactive chat interface for code generation, debugging, and programming assistance with powerful file system tools.

Project Summary

Code Agent is a Go-based CLI tool that enables seamless interaction with Anthropic's Claude AI assistant for programming-related tasks. The application provides a chat interface where users can communicate with Claude while allowing the AI to access and manipulate local files and directories through defined tools.

This project is based on the tutorial from https://ampcode.com/how-to-build-an-agent.

Key Features:

  • Interactive CLI chat interface with Claude AI
  • Persistence of conversation context across exchanges
  • Powerful tool execution capabilities (read_file, list_files, edit_file)
  • Secure API key management
  • Colored terminal output for better user experience
  • File system integration - Claude can read, list, and edit files directly

Technical Implementation:

  • Written in Go with a clean, modular structure
  • Uses Anthropic's official SDK for API communication
  • Implements a tool execution framework where Claude can request to access files
  • Handles the message flow including tool use and results properly
  • Tool-based architecture allowing easy extension with new capabilities

Relation to State of the Art:

This project represents an evolution in AI coding assistants by:

  1. Tool Integration: Unlike basic chat interfaces, Code Agent implements the tool-use capabilities of Claude 3.7 Sonnet, allowing the AI to interact with the user's file system. This bridges the gap between AI assistants and traditional development environments.

  2. Local-First Design: Where many AI coding assistants rely on browser interfaces or cloud environments, Code Agent works directly in the user's terminal with access to local files, maintaining developer workflow and privacy.

  3. Simplified API Interaction: The tool abstracts away the complexity of the Anthropic API, handling authentication, conversation management, and tool execution protocols, making advanced AI capabilities accessible through a simple CLI.

  4. Lightweight Approach: Unlike heavier IDE extensions or plugins, this tool provides AI assistance through a minimal interface that integrates with existing development workflows rather than replacing them.

Code Agent sits at the intersection of traditional command-line tools and modern AI assistants, representing a pragmatic approach to incorporating AI into software development workflows. Its architecture demonstrates the potential for AI agents to operate with controlled access to local resources while maintaining security boundaries.

Features

  • 🤖 Interactive chat with Claude AI
  • 💬 Conversation memory and context
  • 🎨 Colored output for better UX
  • 🔒 Secure API key management
  • 🚀 Simple CLI interface
  • 📁 File system tools - Read, list, and edit files
  • 🔧 Tool execution framework - Claude can use tools automatically

Available Tools

Code Agent provides Claude with several powerful tools to interact with your file system:

📖 read_file - Read File Contents

Description: Read the contents of a file in the working directory.

Usage: Claude can automatically use this tool when you ask about file contents.

Example conversation:

You: What's in main.go?
Claude: I'll check the contents of main.go for you.
tool: read_file({"path":"main.go"})
Claude: Here's what's in main.go:
[file contents displayed]

📋 list_files - List Directory Contents

Description: List files and directories at a given path. If no path is provided, lists files in the current directory.

Usage: Claude uses this to explore your project structure.

Example conversation:

You: What files are in this project?
Claude: Let me check what files are available in the current directory.
tool: list_files({"path":"."})
Claude: Here are the files in your project:
- main.go
- go.mod
- go.sum
- README.md
- config.env.example

✏️ edit_file - Edit File Contents

Description: Make edits to text files by replacing specific text. Can also create new files.

Usage: Claude can modify files directly based on your requests.

Example conversation:

You: Add a comment to the top of main.go explaining what it does
Claude: I'll add a comment to the top of main.go for you.
tool: edit_file({"path":"main.go","old_str":"package main","new_str":"// This is a CLI tool for chatting with Claude AI\npackage main"})
Claude: I've added the comment to main.go successfully.

Parameters:

  • path: The file path to edit
  • old_str: Text to search for (must match exactly)
  • new_str: Text to replace it with
  • If old_str is empty and the file doesn't exist, creates a new file with new_str content

Prerequisites

  • Go 1.19 or higher
  • Anthropic API key

Installation

  1. Clone the repository:
git clone <your-repo-url>cd code-agent
  1. Install dependencies:
go mod tidy
  1. Set up your API key:
# Copy the example config file
cp config.env.example config.env
# Edit config.env and add your actual API key# Get your key from: https://console.anthropic.com/

Usage

Interactive Mode

go run main.go

Build and Run

go build -o code-agent
./code-agent

Example Workflows

Code Review:

You: Review the code in main.go and suggest improvements
Claude: I'll read the main.go file and provide a code review.
[Claude reads the file and provides detailed feedback]

File Organization:

You: List all Go files in the project and suggest a better structure
Claude: Let me explore your project structure first.
[Claude lists files and suggests improvements]

Code Generation:

You: Create a new file called utils.go with helper functions
Claude: I'll create a new utils.go file with some common helper functions.
[Claude creates the file with appropriate content]

Configuration

The application reads your API key from either:

  1. ANTHROPIC_API_KEY environment variable
  2. config.env file

Important: Never commit your actual API key to version control!

Features

  • Conversation Memory: Claude remembers previous messages in the session
  • Error Handling: Graceful handling of API overloads and network issues
  • Colored Output: Blue for user messages, yellow for Claude responses, green for tool usage
  • Graceful Exit: Use Ctrl+C or Ctrl+D to exit
  • Tool Integration: Claude automatically uses appropriate tools when needed
  • File Safety: Tools operate on relative paths within your working directory

Development

Project Structure

code-agent/
├── main.go # Main application code with tool implementations
├── go.mod # Go module file
├── go.sum # Dependency checksums
├── config.env # API key (not in git)
├── config.env.example # Example config
├── .gitignore # Git ignore rules
└── README.md # This file

Adding New Tools

To add a new tool, follow this pattern:

  1. Define the tool input structure:
typeMyToolInputstruct {
Param1string`json:"param1" jsonschema_description:"Description of param1"`Param2int`json:"param2" jsonschema_description:"Description of param2"`
}
  1. Create the tool function:
funcMyTool(input json.RawMessage) (string, error) {
varmyInputMyToolInputerr:=json.Unmarshal(input, &myInput)
iferr!=nil {
return"", fmt.Errorf("invalid input: %w", err)
}
// Tool logic herereturn"result", nil
}
  1. Define the tool:
varMyToolDefinition=ToolDefinition{
Name: "my_tool",
Description: "Description of what this tool does",
InputSchema: GenerateSchema[MyToolInput](),
Function: MyTool,
}
  1. Add to the tools list in main():
tools:= []ToolDefinition{ReadFileDefinition, ListFilesDefinition, EditFileDefinition, MyToolDefinition}

Building

go build -o code-agent

Testing

go test ./...

Security Considerations

  • API keys are stored locally in config.env
  • The .gitignore file prevents accidental commits of sensitive data
  • Environment variables are used for secure key management
  • Tool access is limited to the working directory and subdirectories
  • File operations use relative paths to prevent access to system files

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

Troubleshooting

"tool not found" error: This means Claude tried to use a tool that isn't implemented. Check that all tools are properly added to the tools list in main().

File permission errors: Ensure the application has read/write permissions in the working directory.

API key errors: Verify your API key is correctly set in either the environment variable or config.env file.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

Code Agent

A Go-based CLI tool for interacting with Anthropic's Claude AI assistant. This tool provides an interactive chat interface for code generation, debugging, and programming assistance with powerful file system tools.

Project Summary

Code Agent is a Go-based CLI tool that enables seamless interaction with Anthropic's Claude AI assistant for programming-related tasks. The application provides a chat interface where users can communicate with Claude while allowing the AI to access and manipulate local files and directories through defined tools.

This project is based on the tutorial from https://ampcode.com/how-to-build-an-agent.

Key Features:

  • Interactive CLI chat interface with Claude AI
  • Persistence of conversation context across exchanges
  • Powerful tool execution capabilities (read_file, list_files, edit_file)
  • Secure API key management
  • Colored terminal output for better user experience
  • File system integration - Claude can read, list, and edit files directly

Technical Implementation:

  • Written in Go with a clean, modular structure
  • Uses Anthropic's official SDK for API communication
  • Implements a tool execution framework where Claude can request to access files
  • Handles the message flow including tool use and results properly
  • Tool-based architecture allowing easy extension with new capabilities

Relation to State of the Art:

This project represents an evolution in AI coding assistants by:

  1. Tool Integration: Unlike basic chat interfaces, Code Agent implements the tool-use capabilities of Claude 3.7 Sonnet, allowing the AI to interact with the user's file system. This bridges the gap between AI assistants and traditional development environments.

  2. Local-First Design: Where many AI coding assistants rely on browser interfaces or cloud environments, Code Agent works directly in the user's terminal with access to local files, maintaining developer workflow and privacy.

  3. Simplified API Interaction: The tool abstracts away the complexity of the Anthropic API, handling authentication, conversation management, and tool execution protocols, making advanced AI capabilities accessible through a simple CLI.

  4. Lightweight Approach: Unlike heavier IDE extensions or plugins, this tool provides AI assistance through a minimal interface that integrates with existing development workflows rather than replacing them.

Code Agent sits at the intersection of traditional command-line tools and modern AI assistants, representing a pragmatic approach to incorporating AI into software development workflows. Its architecture demonstrates the potential for AI agents to operate with controlled access to local resources while maintaining security boundaries.

Features

  • 🤖 Interactive chat with Claude AI
  • 💬 Conversation memory and context
  • 🎨 Colored output for better UX
  • 🔒 Secure API key management
  • 🚀 Simple CLI interface
  • 📁 File system tools - Read, list, and edit files
  • 🔧 Tool execution framework - Claude can use tools automatically

Available Tools

Code Agent provides Claude with several powerful tools to interact with your file system:

📖 read_file - Read File Contents

Description: Read the contents of a file in the working directory.

Usage: Claude can automatically use this tool when you ask about file contents.

Example conversation:

You: What's in main.go?
Claude: I'll check the contents of main.go for you.
tool: read_file({"path":"main.go"})
Claude: Here's what's in main.go:
[file contents displayed]

📋 list_files - List Directory Contents

Description: List files and directories at a given path. If no path is provided, lists files in the current directory.

Usage: Claude uses this to explore your project structure.

Example conversation:

You: What files are in this project?
Claude: Let me check what files are available in the current directory.
tool: list_files({"path":"."})
Claude: Here are the files in your project:
- main.go
- go.mod
- go.sum
- README.md
- config.env.example

✏️ edit_file - Edit File Contents

Description: Make edits to text files by replacing specific text. Can also create new files.

Usage: Claude can modify files directly based on your requests.

Example conversation:

You: Add a comment to the top of main.go explaining what it does
Claude: I'll add a comment to the top of main.go for you.
tool: edit_file({"path":"main.go","old_str":"package main","new_str":"// This is a CLI tool for chatting with Claude AI\npackage main"})
Claude: I've added the comment to main.go successfully.

Parameters:

  • path: The file path to edit
  • old_str: Text to search for (must match exactly)
  • new_str: Text to replace it with
  • If old_str is empty and the file doesn't exist, creates a new file with new_str content

Prerequisites

  • Go 1.19 or higher
  • Anthropic API key

Installation

  1. Clone the repository:
git clone <your-repo-url>cd code-agent
  1. Install dependencies:
go mod tidy
  1. Set up your API key:
# Copy the example config file
cp config.env.example config.env
# Edit config.env and add your actual API key# Get your key from: https://console.anthropic.com/

Usage

Interactive Mode

go run main.go

Build and Run

go build -o code-agent
./code-agent

Example Workflows

Code Review:

You: Review the code in main.go and suggest improvements
Claude: I'll read the main.go file and provide a code review.
[Claude reads the file and provides detailed feedback]

File Organization:

You: List all Go files in the project and suggest a better structure
Claude: Let me explore your project structure first.
[Claude lists files and suggests improvements]

Code Generation:

You: Create a new file called utils.go with helper functions
Claude: I'll create a new utils.go file with some common helper functions.
[Claude creates the file with appropriate content]

Configuration

The application reads your API key from either:

  1. ANTHROPIC_API_KEY environment variable
  2. config.env file

Important: Never commit your actual API key to version control!

Features

  • Conversation Memory: Claude remembers previous messages in the session
  • Error Handling: Graceful handling of API overloads and network issues
  • Colored Output: Blue for user messages, yellow for Claude responses, green for tool usage
  • Graceful Exit: Use Ctrl+C or Ctrl+D to exit
  • Tool Integration: Claude automatically uses appropriate tools when needed
  • File Safety: Tools operate on relative paths within your working directory

Development

Project Structure

code-agent/
├── main.go # Main application code with tool implementations
├── go.mod # Go module file
├── go.sum # Dependency checksums
├── config.env # API key (not in git)
├── config.env.example # Example config
├── .gitignore # Git ignore rules
└── README.md # This file

Adding New Tools

To add a new tool, follow this pattern:

  1. Define the tool input structure:
typeMyToolInputstruct {
Param1string`json:"param1" jsonschema_description:"Description of param1"`Param2int`json:"param2" jsonschema_description:"Description of param2"`
}
  1. Create the tool function:
funcMyTool(input json.RawMessage) (string, error) {
varmyInputMyToolInputerr:=json.Unmarshal(input, &myInput)
iferr!=nil {
return"", fmt.Errorf("invalid input: %w", err)
}
// Tool logic herereturn"result", nil
}
  1. Define the tool:
varMyToolDefinition=ToolDefinition{
Name: "my_tool",
Description: "Description of what this tool does",
InputSchema: GenerateSchema[MyToolInput](),
Function: MyTool,
}
  1. Add to the tools list in main():
tools:= []ToolDefinition{ReadFileDefinition, ListFilesDefinition, EditFileDefinition, MyToolDefinition}

Building

go build -o code-agent

Testing

go test ./...

Security Considerations

  • API keys are stored locally in config.env
  • The .gitignore file prevents accidental commits of sensitive data
  • Environment variables are used for secure key management
  • Tool access is limited to the working directory and subdirectories
  • File operations use relative paths to prevent access to system files

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

Troubleshooting

"tool not found" error: This means Claude tried to use a tool that isn't implemented. Check that all tools are properly added to the tools list in main().

File permission errors: Ensure the application has read/write permissions in the working directory.

API key errors: Verify your API key is correctly set in either the environment variable or config.env file.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Code Agent

A Go-based CLI tool for interacting with Anthropic's Claude AI assistant. This tool provides an interactive chat interface for code generation, debugging, and programming assistance with powerful file system tools.

Project Summary

Code Agent is a Go-based CLI tool that enables seamless interaction with Anthropic's Claude AI assistant for programming-related tasks. The application provides a chat interface where users can communicate with Claude while allowing the AI to access and manipulate local files and directories through defined tools.

This project is based on the tutorial from https://ampcode.com/how-to-build-an-agent.

Key Features:

  • Interactive CLI chat interface with Claude AI
  • Persistence of conversation context across exchanges
  • Powerful tool execution capabilities (read_file, list_files, edit_file)
  • Secure API key management
  • Colored terminal output for better user experience
  • File system integration - Claude can read, list, and edit files directly

Technical Implementation:

  • Written in Go with a clean, modular structure
  • Uses Anthropic's official SDK for API communication
  • Implements a tool execution framework where Claude can request to access files
  • Handles the message flow including tool use and results properly
  • Tool-based architecture allowing easy extension with new capabilities

Relation to State of the Art:

This project represents an evolution in AI coding assistants by:

  1. Tool Integration: Unlike basic chat interfaces, Code Agent implements the tool-use capabilities of Claude 3.7 Sonnet, allowing the AI to interact with the user's file system. This bridges the gap between AI assistants and traditional development environments.

  2. Local-First Design: Where many AI coding assistants rely on browser interfaces or cloud environments, Code Agent works directly in the user's terminal with access to local files, maintaining developer workflow and privacy.

  3. Simplified API Interaction: The tool abstracts away the complexity of the Anthropic API, handling authentication, conversation management, and tool execution protocols, making advanced AI capabilities accessible through a simple CLI.

  4. Lightweight Approach: Unlike heavier IDE extensions or plugins, this tool provides AI assistance through a minimal interface that integrates with existing development workflows rather than replacing them.

Code Agent sits at the intersection of traditional command-line tools and modern AI assistants, representing a pragmatic approach to incorporating AI into software development workflows. Its architecture demonstrates the potential for AI agents to operate with controlled access to local resources while maintaining security boundaries.

Features

  • 🤖 Interactive chat with Claude AI
  • 💬 Conversation memory and context
  • 🎨 Colored output for better UX
  • 🔒 Secure API key management
  • 🚀 Simple CLI interface
  • 📁 File system tools - Read, list, and edit files
  • 🔧 Tool execution framework - Claude can use tools automatically

Available Tools

Code Agent provides Claude with several powerful tools to interact with your file system:

📖 read_file - Read File Contents

Description: Read the contents of a file in the working directory.

Usage: Claude can automatically use this tool when you ask about file contents.

Example conversation:

You: What's in main.go?
Claude: I'll check the contents of main.go for you.
tool: read_file({"path":"main.go"})
Claude: Here's what's in main.go:
[file contents displayed]

📋 list_files - List Directory Contents

Description: List files and directories at a given path. If no path is provided, lists files in the current directory.

Usage: Claude uses this to explore your project structure.

Example conversation:

You: What files are in this project?
Claude: Let me check what files are available in the current directory.
tool: list_files({"path":"."})
Claude: Here are the files in your project:
- main.go
- go.mod
- go.sum
- README.md
- config.env.example

✏️ edit_file - Edit File Contents

Description: Make edits to text files by replacing specific text. Can also create new files.

Usage: Claude can modify files directly based on your requests.

Example conversation:

You: Add a comment to the top of main.go explaining what it does
Claude: I'll add a comment to the top of main.go for you.
tool: edit_file({"path":"main.go","old_str":"package main","new_str":"// This is a CLI tool for chatting with Claude AI\npackage main"})
Claude: I've added the comment to main.go successfully.

Parameters:

  • path: The file path to edit
  • old_str: Text to search for (must match exactly)
  • new_str: Text to replace it with
  • If old_str is empty and the file doesn't exist, creates a new file with new_str content

Prerequisites

  • Go 1.19 or higher
  • Anthropic API key

Installation

  1. Clone the repository:
git clone <your-repo-url>cd code-agent
  1. Install dependencies:
go mod tidy
  1. Set up your API key:
# Copy the example config file
cp config.env.example config.env
# Edit config.env and add your actual API key# Get your key from: https://console.anthropic.com/

Usage

Interactive Mode

go run main.go

Build and Run

go build -o code-agent
./code-agent

Example Workflows

Code Review:

You: Review the code in main.go and suggest improvements
Claude: I'll read the main.go file and provide a code review.
[Claude reads the file and provides detailed feedback]

File Organization:

You: List all Go files in the project and suggest a better structure
Claude: Let me explore your project structure first.
[Claude lists files and suggests improvements]

Code Generation:

You: Create a new file called utils.go with helper functions
Claude: I'll create a new utils.go file with some common helper functions.
[Claude creates the file with appropriate content]

Configuration

The application reads your API key from either:

  1. ANTHROPIC_API_KEY environment variable
  2. config.env file

Important: Never commit your actual API key to version control!

Features

  • Conversation Memory: Claude remembers previous messages in the session
  • Error Handling: Graceful handling of API overloads and network issues
  • Colored Output: Blue for user messages, yellow for Claude responses, green for tool usage
  • Graceful Exit: Use Ctrl+C or Ctrl+D to exit
  • Tool Integration: Claude automatically uses appropriate tools when needed
  • File Safety: Tools operate on relative paths within your working directory

Development

Project Structure

code-agent/
├── main.go # Main application code with tool implementations
├── go.mod # Go module file
├── go.sum # Dependency checksums
├── config.env # API key (not in git)
├── config.env.example # Example config
├── .gitignore # Git ignore rules
└── README.md # This file

Adding New Tools

To add a new tool, follow this pattern:

  1. Define the tool input structure:
typeMyToolInputstruct {
Param1string`json:"param1" jsonschema_description:"Description of param1"`Param2int`json:"param2" jsonschema_description:"Description of param2"`
}
  1. Create the tool function:
funcMyTool(input json.RawMessage) (string, error) {
varmyInputMyToolInputerr:=json.Unmarshal(input, &myInput)
iferr!=nil {
return"", fmt.Errorf("invalid input: %w", err)
}
// Tool logic herereturn"result", nil
}
  1. Define the tool:
varMyToolDefinition=ToolDefinition{
Name: "my_tool",
Description: "Description of what this tool does",
InputSchema: GenerateSchema[MyToolInput](),
Function: MyTool,
}
  1. Add to the tools list in main():
tools:= []ToolDefinition{ReadFileDefinition, ListFilesDefinition, EditFileDefinition, MyToolDefinition}

Building

go build -o code-agent

Testing

go test ./...

Security Considerations

  • API keys are stored locally in config.env
  • The .gitignore file prevents accidental commits of sensitive data
  • Environment variables are used for secure key management
  • Tool access is limited to the working directory and subdirectories
  • File operations use relative paths to prevent access to system files

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

Troubleshooting

"tool not found" error: This means Claude tried to use a tool that isn't implemented. Check that all tools are properly added to the tools list in main().

File permission errors: Ensure the application has read/write permissions in the working directory.

API key errors: Verify your API key is correctly set in either the environment variable or config.env file.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Code Agent

A Go-based CLI tool for interacting with Anthropic's Claude AI assistant. This tool provides an interactive chat interface for code generation, debugging, and programming assistance with powerful file system tools.

Project Summary

Code Agent is a Go-based CLI tool that enables seamless interaction with Anthropic's Claude AI assistant for programming-related tasks. The application provides a chat interface where users can communicate with Claude while allowing the AI to access and manipulate local files and directories through defined tools.

This project is based on the tutorial from https://ampcode.com/how-to-build-an-agent.

Key Features:

  • Interactive CLI chat interface with Claude AI
  • Persistence of conversation context across exchanges
  • Powerful tool execution capabilities (read_file, list_files, edit_file)
  • Secure API key management
  • Colored terminal output for better user experience
  • File system integration - Claude can read, list, and edit files directly

Technical Implementation:

  • Written in Go with a clean, modular structure
  • Uses Anthropic's official SDK for API communication
  • Implements a tool execution framework where Claude can request to access files
  • Handles the message flow including tool use and results properly
  • Tool-based architecture allowing easy extension with new capabilities

Relation to State of the Art:

This project represents an evolution in AI coding assistants by:

  1. Tool Integration: Unlike basic chat interfaces, Code Agent implements the tool-use capabilities of Claude 3.7 Sonnet, allowing the AI to interact with the user's file system. This bridges the gap between AI assistants and traditional development environments.

  2. Local-First Design: Where many AI coding assistants rely on browser interfaces or cloud environments, Code Agent works directly in the user's terminal with access to local files, maintaining developer workflow and privacy.

  3. Simplified API Interaction: The tool abstracts away the complexity of the Anthropic API, handling authentication, conversation management, and tool execution protocols, making advanced AI capabilities accessible through a simple CLI.

  4. Lightweight Approach: Unlike heavier IDE extensions or plugins, this tool provides AI assistance through a minimal interface that integrates with existing development workflows rather than replacing them.

Code Agent sits at the intersection of traditional command-line tools and modern AI assistants, representing a pragmatic approach to incorporating AI into software development workflows. Its architecture demonstrates the potential for AI agents to operate with controlled access to local resources while maintaining security boundaries.

Features

  • 🤖 Interactive chat with Claude AI
  • 💬 Conversation memory and context
  • 🎨 Colored output for better UX
  • 🔒 Secure API key management
  • 🚀 Simple CLI interface
  • 📁 File system tools - Read, list, and edit files
  • 🔧 Tool execution framework - Claude can use tools automatically

Available Tools

Code Agent provides Claude with several powerful tools to interact with your file system:

📖 read_file - Read File Contents

Description: Read the contents of a file in the working directory.

Usage: Claude can automatically use this tool when you ask about file contents.

Example conversation:

You: What's in main.go?
Claude: I'll check the contents of main.go for you.
tool: read_file({"path":"main.go"})
Claude: Here's what's in main.go:
[file contents displayed]

📋 list_files - List Directory Contents

Description: List files and directories at a given path. If no path is provided, lists files in the current directory.

Usage: Claude uses this to explore your project structure.

Example conversation:

You: What files are in this project?
Claude: Let me check what files are available in the current directory.
tool: list_files({"path":"."})
Claude: Here are the files in your project:
- main.go
- go.mod
- go.sum
- README.md
- config.env.example

✏️ edit_file - Edit File Contents

Description: Make edits to text files by replacing specific text. Can also create new files.

Usage: Claude can modify files directly based on your requests.

Example conversation:

You: Add a comment to the top of main.go explaining what it does
Claude: I'll add a comment to the top of main.go for you.
tool: edit_file({"path":"main.go","old_str":"package main","new_str":"// This is a CLI tool for chatting with Claude AI\npackage main"})
Claude: I've added the comment to main.go successfully.

Parameters:

  • path: The file path to edit
  • old_str: Text to search for (must match exactly)
  • new_str: Text to replace it with
  • If old_str is empty and the file doesn't exist, creates a new file with new_str content

Prerequisites

  • Go 1.19 or higher
  • Anthropic API key

Installation

  1. Clone the repository:
git clone <your-repo-url>cd code-agent
  1. Install dependencies:
go mod tidy
  1. Set up your API key:
# Copy the example config file
cp config.env.example config.env
# Edit config.env and add your actual API key# Get your key from: https://console.anthropic.com/

Usage

Interactive Mode

go run main.go

Build and Run

go build -o code-agent
./code-agent

Example Workflows

Code Review:

You: Review the code in main.go and suggest improvements
Claude: I'll read the main.go file and provide a code review.
[Claude reads the file and provides detailed feedback]

File Organization:

You: List all Go files in the project and suggest a better structure
Claude: Let me explore your project structure first.
[Claude lists files and suggests improvements]

Code Generation:

You: Create a new file called utils.go with helper functions
Claude: I'll create a new utils.go file with some common helper functions.
[Claude creates the file with appropriate content]

Configuration

The application reads your API key from either:

  1. ANTHROPIC_API_KEY environment variable
  2. config.env file

Important: Never commit your actual API key to version control!

Features

  • Conversation Memory: Claude remembers previous messages in the session
  • Error Handling: Graceful handling of API overloads and network issues
  • Colored Output: Blue for user messages, yellow for Claude responses, green for tool usage
  • Graceful Exit: Use Ctrl+C or Ctrl+D to exit
  • Tool Integration: Claude automatically uses appropriate tools when needed
  • File Safety: Tools operate on relative paths within your working directory

Development

Project Structure

code-agent/
├── main.go # Main application code with tool implementations
├── go.mod # Go module file
├── go.sum # Dependency checksums
├── config.env # API key (not in git)
├── config.env.example # Example config
├── .gitignore # Git ignore rules
└── README.md # This file

Adding New Tools

To add a new tool, follow this pattern:

  1. Define the tool input structure:
typeMyToolInputstruct {
Param1string`json:"param1" jsonschema_description:"Description of param1"`Param2int`json:"param2" jsonschema_description:"Description of param2"`
}
  1. Create the tool function:
funcMyTool(input json.RawMessage) (string, error) {
varmyInputMyToolInputerr:=json.Unmarshal(input, &myInput)
iferr!=nil {
return"", fmt.Errorf("invalid input: %w", err)
}
// Tool logic herereturn"result", nil
}
  1. Define the tool:
varMyToolDefinition=ToolDefinition{
Name: "my_tool",
Description: "Description of what this tool does",
InputSchema: GenerateSchema[MyToolInput](),
Function: MyTool,
}
  1. Add to the tools list in main():
tools:= []ToolDefinition{ReadFileDefinition, ListFilesDefinition, EditFileDefinition, MyToolDefinition}

Building

go build -o code-agent

Testing

go test ./...

Security Considerations

  • API keys are stored locally in config.env
  • The .gitignore file prevents accidental commits of sensitive data
  • Environment variables are used for secure key management
  • Tool access is limited to the working directory and subdirectories
  • File operations use relative paths to prevent access to system files

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

Troubleshooting

"tool not found" error: This means Claude tried to use a tool that isn't implemented. Check that all tools are properly added to the tools list in main().

File permission errors: Ensure the application has read/write permissions in the working directory.

API key errors: Verify your API key is correctly set in either the environment variable or config.env file.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

Code Agent

A Go-based CLI tool for interacting with Anthropic's Claude AI assistant. This tool provides an interactive chat interface for code generation, debugging, and programming assistance with powerful file system tools.

Project Summary

Code Agent is a Go-based CLI tool that enables seamless interaction with Anthropic's Claude AI assistant for programming-related tasks. The application provides a chat interface where users can communicate with Claude while allowing the AI to access and manipulate local files and directories through defined tools.

This project is based on the tutorial from https://ampcode.com/how-to-build-an-agent.

Key Features:

  • Interactive CLI chat interface with Claude AI
  • Persistence of conversation context across exchanges
  • Powerful tool execution capabilities (read_file, list_files, edit_file)
  • Secure API key management
  • Colored terminal output for better user experience
  • File system integration - Claude can read, list, and edit files directly

Technical Implementation:

  • Written in Go with a clean, modular structure
  • Uses Anthropic's official SDK for API communication
  • Implements a tool execution framework where Claude can request to access files
  • Handles the message flow including tool use and results properly
  • Tool-based architecture allowing easy extension with new capabilities

Relation to State of the Art:

This project represents an evolution in AI coding assistants by:

  1. Tool Integration: Unlike basic chat interfaces, Code Agent implements the tool-use capabilities of Claude 3.7 Sonnet, allowing the AI to interact with the user's file system. This bridges the gap between AI assistants and traditional development environments.

  2. Local-First Design: Where many AI coding assistants rely on browser interfaces or cloud environments, Code Agent works directly in the user's terminal with access to local files, maintaining developer workflow and privacy.

  3. Simplified API Interaction: The tool abstracts away the complexity of the Anthropic API, handling authentication, conversation management, and tool execution protocols, making advanced AI capabilities accessible through a simple CLI.

  4. Lightweight Approach: Unlike heavier IDE extensions or plugins, this tool provides AI assistance through a minimal interface that integrates with existing development workflows rather than replacing them.

Code Agent sits at the intersection of traditional command-line tools and modern AI assistants, representing a pragmatic approach to incorporating AI into software development workflows. Its architecture demonstrates the potential for AI agents to operate with controlled access to local resources while maintaining security boundaries.

Features

  • 🤖 Interactive chat with Claude AI
  • 💬 Conversation memory and context
  • 🎨 Colored output for better UX
  • 🔒 Secure API key management
  • 🚀 Simple CLI interface
  • 📁 File system tools - Read, list, and edit files
  • 🔧 Tool execution framework - Claude can use tools automatically

Available Tools

Code Agent provides Claude with several powerful tools to interact with your file system:

📖 read_file - Read File Contents

Description: Read the contents of a file in the working directory.

Usage: Claude can automatically use this tool when you ask about file contents.

Example conversation:

You: What's in main.go?
Claude: I'll check the contents of main.go for you.
tool: read_file({"path":"main.go"})
Claude: Here's what's in main.go:
[file contents displayed]

📋 list_files - List Directory Contents

Description: List files and directories at a given path. If no path is provided, lists files in the current directory.

Usage: Claude uses this to explore your project structure.

Example conversation:

You: What files are in this project?
Claude: Let me check what files are available in the current directory.
tool: list_files({"path":"."})
Claude: Here are the files in your project:
- main.go
- go.mod
- go.sum
- README.md
- config.env.example

✏️ edit_file - Edit File Contents

Description: Make edits to text files by replacing specific text. Can also create new files.

Usage: Claude can modify files directly based on your requests.

Example conversation:

You: Add a comment to the top of main.go explaining what it does
Claude: I'll add a comment to the top of main.go for you.
tool: edit_file({"path":"main.go","old_str":"package main","new_str":"// This is a CLI tool for chatting with Claude AI\npackage main"})
Claude: I've added the comment to main.go successfully.

Parameters:

  • path: The file path to edit
  • old_str: Text to search for (must match exactly)
  • new_str: Text to replace it with
  • If old_str is empty and the file doesn't exist, creates a new file with new_str content

Prerequisites

  • Go 1.19 or higher
  • Anthropic API key

Installation

  1. Clone the repository:
git clone <your-repo-url>cd code-agent
  1. Install dependencies:
go mod tidy
  1. Set up your API key:
# Copy the example config file
cp config.env.example config.env
# Edit config.env and add your actual API key# Get your key from: https://console.anthropic.com/

Usage

Interactive Mode

go run main.go

Build and Run

go build -o code-agent
./code-agent

Example Workflows

Code Review:

You: Review the code in main.go and suggest improvements
Claude: I'll read the main.go file and provide a code review.
[Claude reads the file and provides detailed feedback]

File Organization:

You: List all Go files in the project and suggest a better structure
Claude: Let me explore your project structure first.
[Claude lists files and suggests improvements]

Code Generation:

You: Create a new file called utils.go with helper functions
Claude: I'll create a new utils.go file with some common helper functions.
[Claude creates the file with appropriate content]

Configuration

The application reads your API key from either:

  1. ANTHROPIC_API_KEY environment variable
  2. config.env file

Important: Never commit your actual API key to version control!

Features

  • Conversation Memory: Claude remembers previous messages in the session
  • Error Handling: Graceful handling of API overloads and network issues
  • Colored Output: Blue for user messages, yellow for Claude responses, green for tool usage
  • Graceful Exit: Use Ctrl+C or Ctrl+D to exit
  • Tool Integration: Claude automatically uses appropriate tools when needed
  • File Safety: Tools operate on relative paths within your working directory

Development

Project Structure

code-agent/
├── main.go # Main application code with tool implementations
├── go.mod # Go module file
├── go.sum # Dependency checksums
├── config.env # API key (not in git)
├── config.env.example # Example config
├── .gitignore # Git ignore rules
└── README.md # This file

Adding New Tools

To add a new tool, follow this pattern:

  1. Define the tool input structure:
typeMyToolInputstruct {
Param1string`json:"param1" jsonschema_description:"Description of param1"`Param2int`json:"param2" jsonschema_description:"Description of param2"`
}
  1. Create the tool function:
funcMyTool(input json.RawMessage) (string, error) {
varmyInputMyToolInputerr:=json.Unmarshal(input, &myInput)
iferr!=nil {
return"", fmt.Errorf("invalid input: %w", err)
}
// Tool logic herereturn"result", nil
}
  1. Define the tool:
varMyToolDefinition=ToolDefinition{
Name: "my_tool",
Description: "Description of what this tool does",
InputSchema: GenerateSchema[MyToolInput](),
Function: MyTool,
}
  1. Add to the tools list in main():
tools:= []ToolDefinition{ReadFileDefinition, ListFilesDefinition, EditFileDefinition, MyToolDefinition}

Building

go build -o code-agent

Testing

go test ./...

Security Considerations

  • API keys are stored locally in config.env
  • The .gitignore file prevents accidental commits of sensitive data
  • Environment variables are used for secure key management
  • Tool access is limited to the working directory and subdirectories
  • File operations use relative paths to prevent access to system files

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

Troubleshooting

"tool not found" error: This means Claude tried to use a tool that isn't implemented. Check that all tools are properly added to the tools list in main().

File permission errors: Ensure the application has read/write permissions in the working directory.

API key errors: Verify your API key is correctly set in either the environment variable or config.env file.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Code Agent

A Go-based CLI tool for interacting with Anthropic's Claude AI assistant. This tool provides an interactive chat interface for code generation, debugging, and programming assistance with powerful file system tools.

Project Summary

Code Agent is a Go-based CLI tool that enables seamless interaction with Anthropic's Claude AI assistant for programming-related tasks. The application provides a chat interface where users can communicate with Claude while allowing the AI to access and manipulate local files and directories through defined tools.

This project is based on the tutorial from https://ampcode.com/how-to-build-an-agent.

Key Features:

  • Interactive CLI chat interface with Claude AI
  • Persistence of conversation context across exchanges
  • Powerful tool execution capabilities (read_file, list_files, edit_file)
  • Secure API key management
  • Colored terminal output for better user experience
  • File system integration - Claude can read, list, and edit files directly

Technical Implementation:

  • Written in Go with a clean, modular structure
  • Uses Anthropic's official SDK for API communication
  • Implements a tool execution framework where Claude can request to access files
  • Handles the message flow including tool use and results properly
  • Tool-based architecture allowing easy extension with new capabilities

Relation to State of the Art:

This project represents an evolution in AI coding assistants by:

  1. Tool Integration: Unlike basic chat interfaces, Code Agent implements the tool-use capabilities of Claude 3.7 Sonnet, allowing the AI to interact with the user's file system. This bridges the gap between AI assistants and traditional development environments.

  2. Local-First Design: Where many AI coding assistants rely on browser interfaces or cloud environments, Code Agent works directly in the user's terminal with access to local files, maintaining developer workflow and privacy.

  3. Simplified API Interaction: The tool abstracts away the complexity of the Anthropic API, handling authentication, conversation management, and tool execution protocols, making advanced AI capabilities accessible through a simple CLI.

  4. Lightweight Approach: Unlike heavier IDE extensions or plugins, this tool provides AI assistance through a minimal interface that integrates with existing development workflows rather than replacing them.

Code Agent sits at the intersection of traditional command-line tools and modern AI assistants, representing a pragmatic approach to incorporating AI into software development workflows. Its architecture demonstrates the potential for AI agents to operate with controlled access to local resources while maintaining security boundaries.

Features

  • 🤖 Interactive chat with Claude AI
  • 💬 Conversation memory and context
  • 🎨 Colored output for better UX
  • 🔒 Secure API key management
  • 🚀 Simple CLI interface
  • 📁 File system tools - Read, list, and edit files
  • 🔧 Tool execution framework - Claude can use tools automatically

Available Tools

Code Agent provides Claude with several powerful tools to interact with your file system:

📖 read_file - Read File Contents

Description: Read the contents of a file in the working directory.

Usage: Claude can automatically use this tool when you ask about file contents.

Example conversation:

You: What's in main.go?
Claude: I'll check the contents of main.go for you.
tool: read_file({"path":"main.go"})
Claude: Here's what's in main.go:
[file contents displayed]

📋 list_files - List Directory Contents

Description: List files and directories at a given path. If no path is provided, lists files in the current directory.

Usage: Claude uses this to explore your project structure.

Example conversation:

You: What files are in this project?
Claude: Let me check what files are available in the current directory.
tool: list_files({"path":"."})
Claude: Here are the files in your project:
- main.go
- go.mod
- go.sum
- README.md
- config.env.example

✏️ edit_file - Edit File Contents

Description: Make edits to text files by replacing specific text. Can also create new files.

Usage: Claude can modify files directly based on your requests.

Example conversation:

You: Add a comment to the top of main.go explaining what it does
Claude: I'll add a comment to the top of main.go for you.
tool: edit_file({"path":"main.go","old_str":"package main","new_str":"// This is a CLI tool for chatting with Claude AI\npackage main"})
Claude: I've added the comment to main.go successfully.

Parameters:

  • path: The file path to edit
  • old_str: Text to search for (must match exactly)
  • new_str: Text to replace it with
  • If old_str is empty and the file doesn't exist, creates a new file with new_str content

Prerequisites

  • Go 1.19 or higher
  • Anthropic API key

Installation

  1. Clone the repository:
git clone <your-repo-url>cd code-agent
  1. Install dependencies:
go mod tidy
  1. Set up your API key:
# Copy the example config file
cp config.env.example config.env
# Edit config.env and add your actual API key# Get your key from: https://console.anthropic.com/

Usage

Interactive Mode

go run main.go

Build and Run

go build -o code-agent
./code-agent

Example Workflows

Code Review:

You: Review the code in main.go and suggest improvements
Claude: I'll read the main.go file and provide a code review.
[Claude reads the file and provides detailed feedback]

File Organization:

You: List all Go files in the project and suggest a better structure
Claude: Let me explore your project structure first.
[Claude lists files and suggests improvements]

Code Generation:

You: Create a new file called utils.go with helper functions
Claude: I'll create a new utils.go file with some common helper functions.
[Claude creates the file with appropriate content]

Configuration

The application reads your API key from either:

  1. ANTHROPIC_API_KEY environment variable
  2. config.env file

Important: Never commit your actual API key to version control!

Features

  • Conversation Memory: Claude remembers previous messages in the session
  • Error Handling: Graceful handling of API overloads and network issues
  • Colored Output: Blue for user messages, yellow for Claude responses, green for tool usage
  • Graceful Exit: Use Ctrl+C or Ctrl+D to exit
  • Tool Integration: Claude automatically uses appropriate tools when needed
  • File Safety: Tools operate on relative paths within your working directory

Development

Project Structure

code-agent/
├── main.go # Main application code with tool implementations
├── go.mod # Go module file
├── go.sum # Dependency checksums
├── config.env # API key (not in git)
├── config.env.example # Example config
├── .gitignore # Git ignore rules
└── README.md # This file

Adding New Tools

To add a new tool, follow this pattern:

  1. Define the tool input structure:
typeMyToolInputstruct {
Param1string`json:"param1" jsonschema_description:"Description of param1"`Param2int`json:"param2" jsonschema_description:"Description of param2"`
}
  1. Create the tool function:
funcMyTool(input json.RawMessage) (string, error) {
varmyInputMyToolInputerr:=json.Unmarshal(input, &myInput)
iferr!=nil {
return"", fmt.Errorf("invalid input: %w", err)
}
// Tool logic herereturn"result", nil
}
  1. Define the tool:
varMyToolDefinition=ToolDefinition{
Name: "my_tool",
Description: "Description of what this tool does",
InputSchema: GenerateSchema[MyToolInput](),
Function: MyTool,
}
  1. Add to the tools list in main():
tools:= []ToolDefinition{ReadFileDefinition, ListFilesDefinition, EditFileDefinition, MyToolDefinition}

Building

go build -o code-agent

Testing

go test ./...

Security Considerations

  • API keys are stored locally in config.env
  • The .gitignore file prevents accidental commits of sensitive data
  • Environment variables are used for secure key management
  • Tool access is limited to the working directory and subdirectories
  • File operations use relative paths to prevent access to system files

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

Troubleshooting

"tool not found" error: This means Claude tried to use a tool that isn't implemented. Check that all tools are properly added to the tools list in main().

File permission errors: Ensure the application has read/write permissions in the working directory.

API key errors: Verify your API key is correctly set in either the environment variable or config.env file.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Code Agent

A Go-based CLI tool for interacting with Anthropic's Claude AI assistant. This tool provides an interactive chat interface for code generation, debugging, and programming assistance with powerful file system tools.

Project Summary

Code Agent is a Go-based CLI tool that enables seamless interaction with Anthropic's Claude AI assistant for programming-related tasks. The application provides a chat interface where users can communicate with Claude while allowing the AI to access and manipulate local files and directories through defined tools.

This project is based on the tutorial from https://ampcode.com/how-to-build-an-agent.

Key Features:

  • Interactive CLI chat interface with Claude AI
  • Persistence of conversation context across exchanges
  • Powerful tool execution capabilities (read_file, list_files, edit_file)
  • Secure API key management
  • Colored terminal output for better user experience
  • File system integration - Claude can read, list, and edit files directly

Technical Implementation:

  • Written in Go with a clean, modular structure
  • Uses Anthropic's official SDK for API communication
  • Implements a tool execution framework where Claude can request to access files
  • Handles the message flow including tool use and results properly
  • Tool-based architecture allowing easy extension with new capabilities

Relation to State of the Art:

This project represents an evolution in AI coding assistants by:

  1. Tool Integration: Unlike basic chat interfaces, Code Agent implements the tool-use capabilities of Claude 3.7 Sonnet, allowing the AI to interact with the user's file system. This bridges the gap between AI assistants and traditional development environments.

  2. Local-First Design: Where many AI coding assistants rely on browser interfaces or cloud environments, Code Agent works directly in the user's terminal with access to local files, maintaining developer workflow and privacy.

  3. Simplified API Interaction: The tool abstracts away the complexity of the Anthropic API, handling authentication, conversation management, and tool execution protocols, making advanced AI capabilities accessible through a simple CLI.

  4. Lightweight Approach: Unlike heavier IDE extensions or plugins, this tool provides AI assistance through a minimal interface that integrates with existing development workflows rather than replacing them.

Code Agent sits at the intersection of traditional command-line tools and modern AI assistants, representing a pragmatic approach to incorporating AI into software development workflows. Its architecture demonstrates the potential for AI agents to operate with controlled access to local resources while maintaining security boundaries.

Features

  • 🤖 Interactive chat with Claude AI
  • 💬 Conversation memory and context
  • 🎨 Colored output for better UX
  • 🔒 Secure API key management
  • 🚀 Simple CLI interface
  • 📁 File system tools - Read, list, and edit files
  • 🔧 Tool execution framework - Claude can use tools automatically

Available Tools

Code Agent provides Claude with several powerful tools to interact with your file system:

📖 read_file - Read File Contents

Description: Read the contents of a file in the working directory.

Usage: Claude can automatically use this tool when you ask about file contents.

Example conversation:

You: What's in main.go?
Claude: I'll check the contents of main.go for you.
tool: read_file({"path":"main.go"})
Claude: Here's what's in main.go:
[file contents displayed]

📋 list_files - List Directory Contents

Description: List files and directories at a given path. If no path is provided, lists files in the current directory.

Usage: Claude uses this to explore your project structure.

Example conversation:

You: What files are in this project?
Claude: Let me check what files are available in the current directory.
tool: list_files({"path":"."})
Claude: Here are the files in your project:
- main.go
- go.mod
- go.sum
- README.md
- config.env.example

✏️ edit_file - Edit File Contents

Description: Make edits to text files by replacing specific text. Can also create new files.

Usage: Claude can modify files directly based on your requests.

Example conversation:

You: Add a comment to the top of main.go explaining what it does
Claude: I'll add a comment to the top of main.go for you.
tool: edit_file({"path":"main.go","old_str":"package main","new_str":"// This is a CLI tool for chatting with Claude AI\npackage main"})
Claude: I've added the comment to main.go successfully.

Parameters:

  • path: The file path to edit
  • old_str: Text to search for (must match exactly)
  • new_str: Text to replace it with
  • If old_str is empty and the file doesn't exist, creates a new file with new_str content

Prerequisites

  • Go 1.19 or higher
  • Anthropic API key

Installation

  1. Clone the repository:
git clone <your-repo-url>cd code-agent
  1. Install dependencies:
go mod tidy
  1. Set up your API key:
# Copy the example config file
cp config.env.example config.env
# Edit config.env and add your actual API key# Get your key from: https://console.anthropic.com/

Usage

Interactive Mode

go run main.go

Build and Run

go build -o code-agent
./code-agent

Example Workflows

Code Review:

You: Review the code in main.go and suggest improvements
Claude: I'll read the main.go file and provide a code review.
[Claude reads the file and provides detailed feedback]

File Organization:

You: List all Go files in the project and suggest a better structure
Claude: Let me explore your project structure first.
[Claude lists files and suggests improvements]

Code Generation:

You: Create a new file called utils.go with helper functions
Claude: I'll create a new utils.go file with some common helper functions.
[Claude creates the file with appropriate content]

Configuration

The application reads your API key from either:

  1. ANTHROPIC_API_KEY environment variable
  2. config.env file

Important: Never commit your actual API key to version control!

Features

  • Conversation Memory: Claude remembers previous messages in the session
  • Error Handling: Graceful handling of API overloads and network issues
  • Colored Output: Blue for user messages, yellow for Claude responses, green for tool usage
  • Graceful Exit: Use Ctrl+C or Ctrl+D to exit
  • Tool Integration: Claude automatically uses appropriate tools when needed
  • File Safety: Tools operate on relative paths within your working directory

Development

Project Structure

code-agent/
├── main.go # Main application code with tool implementations
├── go.mod # Go module file
├── go.sum # Dependency checksums
├── config.env # API key (not in git)
├── config.env.example # Example config
├── .gitignore # Git ignore rules
└── README.md # This file

Adding New Tools

To add a new tool, follow this pattern:

  1. Define the tool input structure:
typeMyToolInputstruct {
Param1string`json:"param1" jsonschema_description:"Description of param1"`Param2int`json:"param2" jsonschema_description:"Description of param2"`
}
  1. Create the tool function:
funcMyTool(input json.RawMessage) (string, error) {
varmyInputMyToolInputerr:=json.Unmarshal(input, &myInput)
iferr!=nil {
return"", fmt.Errorf("invalid input: %w", err)
}
// Tool logic herereturn"result", nil
}
  1. Define the tool:
varMyToolDefinition=ToolDefinition{
Name: "my_tool",
Description: "Description of what this tool does",
InputSchema: GenerateSchema[MyToolInput](),
Function: MyTool,
}
  1. Add to the tools list in main():
tools:= []ToolDefinition{ReadFileDefinition, ListFilesDefinition, EditFileDefinition, MyToolDefinition}

Building

go build -o code-agent

Testing

go test ./...

Security Considerations

  • API keys are stored locally in config.env
  • The .gitignore file prevents accidental commits of sensitive data
  • Environment variables are used for secure key management
  • Tool access is limited to the working directory and subdirectories
  • File operations use relative paths to prevent access to system files

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

Troubleshooting

"tool not found" error: This means Claude tried to use a tool that isn't implemented. Check that all tools are properly added to the tools list in main().

File permission errors: Ensure the application has read/write permissions in the working directory.

API key errors: Verify your API key is correctly set in either the environment variable or config.env file.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

Code Agent

A Go-based CLI tool for interacting with Anthropic's Claude AI assistant. This tool provides an interactive chat interface for code generation, debugging, and programming assistance with powerful file system tools.

Project Summary

Code Agent is a Go-based CLI tool that enables seamless interaction with Anthropic's Claude AI assistant for programming-related tasks. The application provides a chat interface where users can communicate with Claude while allowing the AI to access and manipulate local files and directories through defined tools.

This project is based on the tutorial from https://ampcode.com/how-to-build-an-agent.

Key Features:

  • Interactive CLI chat interface with Claude AI
  • Persistence of conversation context across exchanges
  • Powerful tool execution capabilities (read_file, list_files, edit_file)
  • Secure API key management
  • Colored terminal output for better user experience
  • File system integration - Claude can read, list, and edit files directly

Technical Implementation:

  • Written in Go with a clean, modular structure
  • Uses Anthropic's official SDK for API communication
  • Implements a tool execution framework where Claude can request to access files
  • Handles the message flow including tool use and results properly
  • Tool-based architecture allowing easy extension with new capabilities

Relation to State of the Art:

This project represents an evolution in AI coding assistants by:

  1. Tool Integration: Unlike basic chat interfaces, Code Agent implements the tool-use capabilities of Claude 3.7 Sonnet, allowing the AI to interact with the user's file system. This bridges the gap between AI assistants and traditional development environments.

  2. Local-First Design: Where many AI coding assistants rely on browser interfaces or cloud environments, Code Agent works directly in the user's terminal with access to local files, maintaining developer workflow and privacy.

  3. Simplified API Interaction: The tool abstracts away the complexity of the Anthropic API, handling authentication, conversation management, and tool execution protocols, making advanced AI capabilities accessible through a simple CLI.

  4. Lightweight Approach: Unlike heavier IDE extensions or plugins, this tool provides AI assistance through a minimal interface that integrates with existing development workflows rather than replacing them.

Code Agent sits at the intersection of traditional command-line tools and modern AI assistants, representing a pragmatic approach to incorporating AI into software development workflows. Its architecture demonstrates the potential for AI agents to operate with controlled access to local resources while maintaining security boundaries.

Features

  • 🤖 Interactive chat with Claude AI
  • 💬 Conversation memory and context
  • 🎨 Colored output for better UX
  • 🔒 Secure API key management
  • 🚀 Simple CLI interface
  • 📁 File system tools - Read, list, and edit files
  • 🔧 Tool execution framework - Claude can use tools automatically

Available Tools

Code Agent provides Claude with several powerful tools to interact with your file system:

📖 read_file - Read File Contents

Description: Read the contents of a file in the working directory.

Usage: Claude can automatically use this tool when you ask about file contents.

Example conversation:

You: What's in main.go?
Claude: I'll check the contents of main.go for you.
tool: read_file({"path":"main.go"})
Claude: Here's what's in main.go:
[file contents displayed]

📋 list_files - List Directory Contents

Description: List files and directories at a given path. If no path is provided, lists files in the current directory.

Usage: Claude uses this to explore your project structure.

Example conversation:

You: What files are in this project?
Claude: Let me check what files are available in the current directory.
tool: list_files({"path":"."})
Claude: Here are the files in your project:
- main.go
- go.mod
- go.sum
- README.md
- config.env.example

✏️ edit_file - Edit File Contents

Description: Make edits to text files by replacing specific text. Can also create new files.

Usage: Claude can modify files directly based on your requests.

Example conversation:

You: Add a comment to the top of main.go explaining what it does
Claude: I'll add a comment to the top of main.go for you.
tool: edit_file({"path":"main.go","old_str":"package main","new_str":"// This is a CLI tool for chatting with Claude AI\npackage main"})
Claude: I've added the comment to main.go successfully.

Parameters:

  • path: The file path to edit
  • old_str: Text to search for (must match exactly)
  • new_str: Text to replace it with
  • If old_str is empty and the file doesn't exist, creates a new file with new_str content

Prerequisites

  • Go 1.19 or higher
  • Anthropic API key

Installation

  1. Clone the repository:
git clone <your-repo-url>cd code-agent
  1. Install dependencies:
go mod tidy
  1. Set up your API key:
# Copy the example config file
cp config.env.example config.env
# Edit config.env and add your actual API key# Get your key from: https://console.anthropic.com/

Usage

Interactive Mode

go run main.go

Build and Run

go build -o code-agent
./code-agent

Example Workflows

Code Review:

You: Review the code in main.go and suggest improvements
Claude: I'll read the main.go file and provide a code review.
[Claude reads the file and provides detailed feedback]

File Organization:

You: List all Go files in the project and suggest a better structure
Claude: Let me explore your project structure first.
[Claude lists files and suggests improvements]

Code Generation:

You: Create a new file called utils.go with helper functions
Claude: I'll create a new utils.go file with some common helper functions.
[Claude creates the file with appropriate content]

Configuration

The application reads your API key from either:

  1. ANTHROPIC_API_KEY environment variable
  2. config.env file

Important: Never commit your actual API key to version control!

Features

  • Conversation Memory: Claude remembers previous messages in the session
  • Error Handling: Graceful handling of API overloads and network issues
  • Colored Output: Blue for user messages, yellow for Claude responses, green for tool usage
  • Graceful Exit: Use Ctrl+C or Ctrl+D to exit
  • Tool Integration: Claude automatically uses appropriate tools when needed
  • File Safety: Tools operate on relative paths within your working directory

Development

Project Structure

code-agent/
├── main.go # Main application code with tool implementations
├── go.mod # Go module file
├── go.sum # Dependency checksums
├── config.env # API key (not in git)
├── config.env.example # Example config
├── .gitignore # Git ignore rules
└── README.md # This file

Adding New Tools

To add a new tool, follow this pattern:

  1. Define the tool input structure:
typeMyToolInputstruct {
Param1string`json:"param1" jsonschema_description:"Description of param1"`Param2int`json:"param2" jsonschema_description:"Description of param2"`
}
  1. Create the tool function:
funcMyTool(input json.RawMessage) (string, error) {
varmyInputMyToolInputerr:=json.Unmarshal(input, &myInput)
iferr!=nil {
return"", fmt.Errorf("invalid input: %w", err)
}
// Tool logic herereturn"result", nil
}
  1. Define the tool:
varMyToolDefinition=ToolDefinition{
Name: "my_tool",
Description: "Description of what this tool does",
InputSchema: GenerateSchema[MyToolInput](),
Function: MyTool,
}
  1. Add to the tools list in main():
tools:= []ToolDefinition{ReadFileDefinition, ListFilesDefinition, EditFileDefinition, MyToolDefinition}

Building

go build -o code-agent

Testing

go test ./...

Security Considerations

  • API keys are stored locally in config.env
  • The .gitignore file prevents accidental commits of sensitive data
  • Environment variables are used for secure key management
  • Tool access is limited to the working directory and subdirectories
  • File operations use relative paths to prevent access to system files

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

Troubleshooting

"tool not found" error: This means Claude tried to use a tool that isn't implemented. Check that all tools are properly added to the tools list in main().

File permission errors: Ensure the application has read/write permissions in the working directory.

API key errors: Verify your API key is correctly set in either the environment variable or config.env file.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages