# Check Node versionnode --version # needs v18+# Install the SDKnpm install @anthropic-ai/claude-code
# Set your API key (required)exportANTHROPIC_API_KEY=sk-ant-xxxxxxxxxx
// src/hello.ts
import{query}from'@anthropic-ai/claude-code';constconversation=query({prompt:'List the three largest source files in this repo and explain each in one sentence.',options:{cwd: process.cwd(),permissionMode:'default'}});forawait(consteventofconversation){if(event.type==='text')process.stdout.write(event.text);}
import{query,typeConversationEvent}from'@anthropic-ai/claude-code';constconversation=query({prompt:'What files are in this directory?',options:{cwd: process.cwd(),permissionMode:'acceptEdits'}});forawait(consteventofconversation){switch(event.type){case'text':// The model's text output, streamed token-by-token
process.stdout.write(event.text);break;case'tool_use':// The model is calling a tool
console.log(`\n[Tool] ${event.name}(${JSON.stringify(event.input)})`);break;case'tool_result':// A tool returned its result
console.log(`[Result] ${event.content?.substring(0,100)}...`);break;case'error':// Something went wrong
console.error(`[Error] ${event.error}`);break;case'done':// Conversation complete
console.log('\n[Done]');break;}}
import{query}from'@anthropic-ai/claude-code';asyncfunctiongetResponse(prompt: string):Promise<string>{constconversation=query({prompt,options:{cwd: process.cwd(),permissionMode:'acceptEdits'}});constparts: string[]=[];forawait(consteventofconversation){if(event.type==='text'){parts.push(event.text);}}returnparts.join('');}constanalysis=awaitgetResponse('Analyze the error handling in src/api.ts');console.log(analysis);
// Read-only: no writes, no shell
constreadOnly=async(tool: string)=>tool==='Read'?'allow':'deny';// Edit-only: reads + writes, no shell
consteditOnly=async(tool: string)=>['Read','Write','Edit'].includes(tool)?'allow':'deny';// Project-scoped: anything within the project, nothing outside
constprojectScoped=async(tool: string,input: any)=>{if(tool==='Read')return'allow';if(tool==='Write'||tool==='Edit'){constpath=input.file_path||'';returnpath.startsWith(process.cwd())?'allow':'deny';}if(tool==='Bash'){constcmd=input.command||'';// Block commands that could escape the project
if(/\/(etc|usr|var|root)/.test(cmd))return'deny';return'allow';}return'deny';};
import{query}from'@anthropic-ai/claude-code';import{execSync}from'child_process';constlastTag=execSync('git describe --tags --abbrev=0').toString().trim();constcommits=execSync(`git log ${lastTag}..HEAD --oneline`).toString();if(!commits.trim()){console.log('No new commits since',lastTag);process.exit(0);}console.log(`Updating CHANGELOG for commits since ${lastTag}...`);console.log(`Found ${commits.trim().split('\n').length} commits\n`);constconversation=query({prompt:`
Update CHANGELOG.md with a new entry for an upcoming release.
The commits since ${lastTag} are:
${commits} Group them into Added/Changed/Fixed/Removed following Keep a Changelog format.
Use semantic versioning to suggest the next version.
Edit CHANGELOG.md in place. Do not create a new file.
Today's date is ${newDate().toISOString().split('T')[0]}.
`,options:{cwd: process.cwd(),permissionMode:'acceptEdits'}});forawait(consteventofconversation){if(event.type==='text')process.stdout.write(event.text);}console.log('\n\nCHANGELOG updated. Review with: git diff CHANGELOG.md');
// scripts/audit-deps.ts
import{query}from'@anthropic-ai/claude-code';constconversation=query({prompt:`
Audit this project's dependencies:
1. Read package.json
2. Run 'npm audit' and analyze the results
3. Check for outdated packages with 'npm outdated'
4. Identify any dependencies that are deprecated or unmaintained
5. Give me a prioritized list of actions (critical security fixes first)
`,options:{cwd: process.cwd(),permissionMode:'custom',permissionCallback: async(tool,input)=>{if(tool==='Read')return'allow';if(tool==='Bash'){constcmd=input.command||'';if(/^npm (audit|outdated|ls|list)/.test(cmd))return'allow';if(/^(cat|grep|jq)/.test(cmd))return'allow';}return'deny';}}});forawait(consteventofconversation){if(event.type==='text')process.stdout.write(event.text);}
// scripts/refactor.ts
import{query}from'@anthropic-ai/claude-code';consttask=process.argv[2];if(!task){console.error('Usage: npx tsx scripts/refactor.ts "description of refactoring"');process.exit(1);}console.log(`Starting refactoring: ${task}\n`);constconversation=query({prompt:`
Perform the following refactoring across this codebase:
${task} Rules:
- Make changes file by file
- Run tests after each significant change
- If tests break, fix them before moving on
- Do not change public API signatures unless that's the explicit goal
- Commit each logical change separately with a clear message
`,options:{cwd: process.cwd(),permissionMode:'acceptEdits'}});forawait(consteventofconversation){if(event.type==='text')process.stdout.write(event.text);}console.log('\n\nRefactoring complete. Review with: git log --oneline -10');
用法:
1
2
3
npx tsx scripts/refactor.ts "Rename UserService to AccountService everywhere"npx tsx scripts/refactor.ts "Convert all callback-based functions in src/utils/ to async/await"npx tsx scripts/refactor.ts "Add TypeScript strict null checks and fix all resulting errors"
# .github/workflows/claude-full.ymlname:Claude Code Assistanton:# Respond to @claude in PR commentspull_request_review_comment:types:[created]issue_comment:types:[created]# Auto-review new PRspull_request:types:[opened, synchronize]jobs:# Job 1: Respond to @claude mentionsrespond:if:> (github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment')
&& contains(github.event.comment.body, '@claude')runs-on:ubuntu-latestpermissions:contents:writepull-requests:writeissues:writesteps:- uses:actions/checkout@v4with:ref:${{ github.head_ref }}fetch-depth:0- uses:anthropic/claude-code-action@v1with:anthropic-api-key:${{ secrets.ANTHROPIC_API_KEY }}max-turns:20timeout-minutes:15# Job 2: Auto-review new PRsauto-review:if:github.event_name == 'pull_request'runs-on:ubuntu-latestpermissions:contents:readpull-requests:writesteps:- uses:actions/checkout@v4with:fetch-depth:0- uses:anthropic/claude-code-action@v1with:anthropic-api-key:${{ secrets.ANTHROPIC_API_KEY }}prompt:| Review this PR. Focus on:
1. Correctness and logic errors
2. Security issues
3. Performance concerns
4. Missing tests for new functionality
Leave your review as a PR review with specific file/line comments.max-turns:10timeout-minutes:10
Claude Code reviews PR #42: "Add user authentication middleware"
---
## Review Summary
### Critical Issues
**1. Missing rate limiting (src/middleware/auth.ts:45)**The authentication middleware doesn't rate-limit failed attempts.
An attacker could brute-force tokens. Consider adding:
import rateLimit from 'express-rate-limit';
const authLimiter = rateLimit({ windowMs: 15*60*1000, max: 100 });
**2. Token stored in localStorage (src/utils/auth.ts:12)**localStorage is vulnerable to XSS. Consider httpOnly cookies instead.
### Suggestions
- Add tests for the token refresh flow (currently untested)
- The `validateToken` function swallows errors silently — log them
- Consider extracting the JWT config to environment variables
### What looks good
- Clean separation of auth middleware from business logic
- Good use of TypeScript generics in the token types
- Test coverage for the happy path is solid
审查者阅读 Claude 的分析,解决关键问题,并回复:
1
2
3
@claude good catches. Please fix the rate limiting issue — add express-rate-limit
to the auth middleware with a 100 requests per 15 minute window. Also add a test
for it.
Claude 读取评论,检出分支,进行修改,运行测试,并推送一个提交:
1
2
3
4
5
6
7
8
9
I've made the following changes:
1. Added `express-rate-limit` dependency
2. Applied rate limiting to the auth middleware (100 req / 15 min window)
3. Added test in `tests/middleware/auth.test.ts` for rate limiting behavior
Commit: abc1234 "Add rate limiting to auth middleware"
All tests pass (47 passed, 0 failed).
# .github/workflows/claude-check.ymlname:Claude Pre-merge Checkon:pull_request:types:[opened, synchronize]branches:[main]jobs:security-check:runs-on:ubuntu-latestpermissions:contents:readpull-requests:writesteps:- uses:actions/checkout@v4with:fetch-depth:0- uses:anthropic/claude-code-action@v1with:anthropic-api-key:${{ secrets.ANTHROPIC_API_KEY }}prompt:| Review the diff in this PR for security issues only.
Check for:
- Hardcoded secrets or credentials
- SQL injection vulnerabilities
- XSS vulnerabilities
- Insecure deserialization
- Path traversal
- Command injection
If you find any security issues, leave a review requesting changes.
If the code is clean, approve the PR.max-turns:10
# .github/workflows/claude-docs.ymlname:Auto-update Docson:push:branches:[main]paths:- 'src/api/**'- 'src/models/**'jobs:update-docs:runs-on:ubuntu-latestpermissions:contents:writepull-requests:writesteps:- uses:actions/checkout@v4- uses:anthropic/claude-code-action@v1with:anthropic-api-key:${{ secrets.ANTHROPIC_API_KEY }}prompt:| The API or model files have changed. Update the API documentation:
1. Read the changed files in src/api/ and src/models/
2. Update docs/api-reference.md to reflect the current state
3. If any endpoints were added/removed/changed, update the table
4. Create a PR with the documentation updatesmax-turns:15
# .github/workflows/release-notes.ymlname:Generate Release Noteson:release:types:[created]jobs:notes:runs-on:ubuntu-latestpermissions:contents:writesteps:- uses:actions/checkout@v4with:fetch-depth:0- uses:anthropic/claude-code-action@v1with:anthropic-api-key:${{ secrets.ANTHROPIC_API_KEY }}prompt:| Generate release notes for ${{ github.event.release.tag_name }}.
Look at commits since the previous tag.
Group changes by category (Features, Fixes, Breaking Changes).
Format for GitHub release notes (markdown).
Update the release body using gh CLI.max-turns:10
import{query}from'@anthropic-ai/claude-code';asyncfunctionmultiTurn(turns: string[]){letcontext='';for(constturnofturns){constfullPrompt=context?`Previous context:\n${context}\n\nNew instruction:\n${turn}`:turn;constparts: string[]=[];constconversation=query({prompt: fullPrompt,options:{cwd: process.cwd(),permissionMode:'acceptEdits'}});forawait(consteventofconversation){if(event.type==='text'){process.stdout.write(event.text);parts.push(event.text);}}context+=`\nTurn: ${turn}\nResponse: ${parts.join('')}\n`;console.log('\n---\n');}}awaitmultiTurn(['Read src/api/users.ts and identify any potential issues','Fix the issues you identified and add error handling','Write tests for the changes you made']);
import{query}from'@anthropic-ai/claude-code';asyncfunctionrunTask(name: string,prompt: string):Promise<string>{constparts: string[]=[];constconversation=query({prompt,options:{cwd: process.cwd(),permissionMode:'default'}});forawait(consteventofconversation){if(event.type==='text')parts.push(event.text);}return`## ${name}\n${parts.join('')}`;}// Run analyses in parallel
constresults=awaitPromise.all([runTask('Security','Audit this codebase for security vulnerabilities. Read key files.'),runTask('Performance','Identify performance bottlenecks in the hot paths. Check database queries.'),runTask('Debt','Find the top 5 areas of technical debt. Look for TODO comments and complex functions.'),]);console.log(results.join('\n\n---\n\n'));
import{query}from'@anthropic-ai/claude-code';import{createWriteStream}from'fs';constoutputFile=createWriteStream('analysis-output.md');constconversation=query({prompt:'Do a comprehensive architecture review of this project.',options:{cwd: process.cwd(),permissionMode:'default'}});forawait(consteventofconversation){if(event.type==='text'){process.stdout.write(event.text);outputFile.write(event.text);}}outputFile.end();console.log('\n\nOutput saved to analysis-output.md');