Compare commits

..

64 Commits

Author SHA1 Message Date
Andrei Edell 98b5285628 run prettier correctly on generated protos 2025-05-08 13:10:14 -10:00
canvrno 7b416ccc70 Feat: Task Favorites ️ (#3392)
* Task Favorites

* Task management docs
2025-05-08 15:49:05 -07:00
Alex 29f3cfa894 Update index.css (#3367) 2025-05-09 03:18:53 +05:30
Ara 978f34e30b Supporting implicit Caching in Gemini (#3394)
* Refactor GeminiHandler to remove caching logic and update pricing structure

* Removed the enhanced caching system and related logic from GeminiHandler.
* Updated the pricing structure for cache reads in both geminiModels and vertexModels.
* Simplified the message creation process by eliminating unnecessary cache checks and operations.

* Fixing Gemini and vertex cache pricing

* Fixing Gemini and vertex cache pricing

* Update src/api/providers/gemini.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-09 03:17:41 +05:30
canvrno 445e25221a [PROTOBUS] Move requestVsCodeLmModels to protobus (#3344)
* Task Favorites

* getOllamaModels protobus migration

* VsCodeLmModels protobus migration

* cleanup
2025-05-08 10:50:23 -10:00
Ara 489a05117c Increasing file sizes for files that can be read by cline (#3396)
* Increasing file sizes for files that can be read by cline

* Update src/integrations/misc/extract-text.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Increasing file sizes for files that can be read by cline

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-08 12:55:40 -07:00
WinterYukky e572ee44f9 fix(bedrock): application inference profile is not work (#3388)
* fix(bedrock): application inference profile is not work

* chore: add change set

* chore: change the encoding condition to whether it contains a slash
2025-05-09 00:26:05 +05:30
pashpashpash f4e14bfe3b removing sparkle from command name (#3395)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-09 00:16:40 +05:30
watany bddc1b5e96 fix(bedrock); update bedrock api (#3157)
* fix nova

* haiku

* changeset

* changeset

* clean up duplicate changeset

* commented caching write
2025-05-08 10:52:08 -07:00
pashpashpash cb0de8f17e tracking models in diff edit failures (#3297)
* tracking models in diff edit failures

* prettier

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-08 12:33:29 -05:00
Evan e1a0b244de Conditionally initialize posthog webview (#3381)
* conditionally initialize posthog client webview

* changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-08 12:08:40 -05:00
Dennis Bartlett a9d5411bf0 Revert "Update deployer team name (#3377)" 2025-05-08 06:57:18 -05:00
Dennis Bartlett 16af9125ec Update variable name (#3384) 2025-05-08 06:51:55 -05:00
Ara 2792e7698f Raise Errors when users try to upload images larger than 7500x7500 pixels (#3336)
* Adding iamge dimension check

* Adding iamge dimension check

* Adding iamge dimension check

* Adding iamge dimension check

* Adding iamge dimension check

* Adding iamge dimension check
2025-05-07 23:48:04 -07:00
Wesley Smith d02e5a89e5 fix excessive markdown format character escaping (#3355)
* fix excessive markdown format character escaping

* add changeset

* made it a little more robust

---------

Co-authored-by: Wesley Smith <wes@neofactory.ai>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-07 22:31:31 -07:00
Dennis Bartlett 20f19917d3 Add org to team affiliation check (#3380) 2025-05-08 00:01:42 -05:00
Evan 7e5cd52864 Always allow textarea typing (#3356)
* enable text area while cline is doing stuff

* changeset

* add sendingDisabled to dependency array

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-07 22:01:07 -07:00
pashpashpash 4622ad767b Copy buttons (#3373)
* copy button in task header

* changeset

* added copy buttons to assistant messages that show up on hover

* added aria

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-07 21:59:42 -07:00
Dennis Bartlett 96048d5ac5 Update deployer team name (#3377)
* Update deployer team name

* Create clever-balloons-wave.md
2025-05-07 23:37:33 -05:00
Ara facec93082 Adding Mistral 3 medium model (#3366)
* Fixing Gemini and vertex cache pricing

* Fixing Gemini and vertex cache pricing
2025-05-08 05:46:09 +05:30
Saoud Rizwan c040be9eb1 Disables autocaptures when initializing feature flags 2025-05-07 15:55:33 -05:00
Evan 8d3cf53289 Docs: image links (#3350)
* add cdn image links

* changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-07 13:41:42 -05:00
Trevor Hudson 83c4a82e6d Diable auto track (#3364)
* disable autocatpure

* changeset
2025-05-07 11:32:33 -07:00
Toshii 6ad11badf3 Systematic selection of gemini models w/ caching (#3343)
* no more updating gemini models

* changeset
2025-05-07 10:07:45 -07:00
Tomás Barreiro 39c7da301c fix path tests on windows (#3276) 2025-05-07 22:22:58 +05:30
DrobConsulting 5275f2eabc Updated OpenAiHandler to support Azure GCC region (#3235)
- Added a check for azureApiVersion to determine if the endpoint is an Azure endpoint.
    - Included conditions to check for 'azure.com' and 'azure.us' in the openAiBaseUrl.
    - Ensured that the openAiModelId does not include 'deepseek' when determining the Azure endpoint.
2025-05-07 01:06:12 -07:00
Caleb Eom 7cf68ff279 Improve time display and filter out resume_task in Task Timeline (#3333)
* Improve time display and filter out resume_task in Task Timeline

* changeset

* polishing it up a little

* a little bigger

* more tooltips + task header

* further refinement

* spacing

* moving delete button up one row conditionally

* removed log

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-07 02:02:41 -05:00
Evan b8af02ebaa Stop doomscrolling (#3354)
* disable auto scroll on user scroll up

* changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-07 01:29:57 -05:00
Ara 904df9f361 Enhance DiffViewProvider to preserve focus when opening text documents (#3346) 2025-05-06 22:52:44 -05:00
canvrno ca3cf185cf [PROTOBUS] Move showTaskWithID to protobus (#3283)
* showTaskWithID protobus migration

* replaced ShowTaskWithIdRequest with generic stringRequest

* prettier
2025-05-06 19:21:37 -07:00
canvrno a02bf11c81 getLmStudioModels protobus migration (#3341) 2025-05-06 19:21:17 -07:00
canvrno 5f4b8078dc reenable tests in workflow (#3347) 2025-05-06 19:16:11 -07:00
monotykamary 1f573955ff feat: add gemini-2.5-pro-preview-05-06 model (#3332)
* feat: add gemini-2.5-pro-preview-05-06 model

* chore: remove gemini-2.5-pro-preview-03-25
2025-05-06 16:36:40 -07:00
zapp88 dbba0ef776 Ability to generate commit message with cline. (#3318)
* Add handling of git message

*  Add commit message generation feature

- Implemented commit message generation functionality in controller
- Added new command to generate commit messages from git diff
- Added error handling for commit message generation
- Updated API handler to support commit message generation
- Added new icon for commit message command
- Updated keybindings for commit message generation
- Added command to command palette for easier access
- Improved error handling and logging
- Added support for generating commit messages from staged changes
- Updated documentation and comments

* Handle user dismissing the dialog (selectedAction is undefined)

* Apply code review suggestions

No default keybinding
The task is not cancelable
Unused import removed
Cleaner message
2025-05-06 16:26:35 -07:00
Evan d14345f605 Feature Flags Node (#3312)
* add featureFlagProvider service

* changeset

* import telemetryService

---------

Co-authored-by: Elephant Lumps <celestial_vault@mac.mynetworksettings.com>
Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-06 16:26:00 -07:00
user202729 2059e84701 Add audio type to McpToolCallResponse (#3289) 2025-05-06 16:25:37 -07:00
José Luis Di Biase f4a9d5f4f3 Bump ollama from 0.5.13 to 0.5.15: To support proxy/Basic auth (#3335) 2025-05-06 16:22:25 -07:00
Toshii 6303a77e8a Update Cline provider trending model (#3345)
* change recommended model

* changeset
2025-05-06 15:03:01 -07:00
Toshii 2963aa5e93 fetch cache details from OR/Cline provider generation endpoint (#3340)
* fetch cache details from generation endpoint

* changeset
2025-05-06 14:25:45 -07:00
Andrei Eternal cfc133acd3 PROTOBUS: Streaming, State, Service Auto-Config (#3253)
* round 1

* round 2 - searchFiles integration attempt

* undo streaming search experiments

* Start state.proto and related migrations

* state subscription

* get the main state flow using it

* correct stream ending early, debug statements

* clean up build-proto service config

* autogenerate index.tses

* auto-generate grpc-client service exports

* rename web-content -> web to make codegen work

* cleaned up streaming flow & cancels

* v3.14.0 Release Notes

v3.14.0 Release Notes

* prettier

* uhh prettier ?

* rename GrpcRequestRegistry file

* auto-generate directory for new services in the config

* generate template proto if it doesn't exist and provide instructions

* format fix

* add models service back to new system

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-05-06 13:42:36 -07:00
Evan 311cb3ac0a Rest of docs (#3339)
* add enterprise section to new docs

* changeset

* migrate mcp docs

* changeset

* migrate more info section

* changeset

* reorder entries

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.attlocal.net>
Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
Co-authored-by: Elephant Lumps <celestial_vault@mac.mynetworksettings.com>
2025-05-06 15:14:53 -05:00
canvrno 06fc419a15 searchFiles protobus migration (#3261) 2025-05-06 11:40:38 -07:00
Evan 10f7b8ca9e Migrate custom model configs section new docs (#3304)
* migrate custom model config section

* changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@mac.mynetworksettings.com>
Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-06 11:16:54 -07:00
Evan bc9eaeeff7 Migrate running models locally section new docs (#3305)
* migrate run models locally section

* changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@mac.mynetworksettings.com>
Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-06 11:16:34 -07:00
canvrno 94fc619196 [PROTOBUS] Move exportTaskWithId to protobus (#3285)
* exportTaskWithId protobus migration

* rebase fixes
2025-05-06 11:06:37 -07:00
canvrno 7084e74372 getOllamaModels protobus migration (#3317) 2025-05-06 11:06:01 -07:00
Toshii dd35bce141 Breakpoint just in first user message for gemini for OR and cline provider (#3319)
* breakpoint just in system prompt

* changeset

* user message included
2025-05-06 08:50:22 -07:00
Caleb Eom f1ed93add8 Task timeline (#3264)
* v3.14.0 Release Notes

v3.14.0 Release Notes

* Task Timeline

* Task Timeline

* Formatting Plan Mode Respond

* changeset

* Update webview-ui/src/components/chat/TaskTimeline.tsx

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Default scroll to right. Change read file colour

* Fixing Colour coding, and adding hover state in tool tip

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-06 15:47:19 +05:30
David Nanyan a43da8d66b Allow users to create issue via CLI with prefilled system and os info (#3250)
* Change bug report template

* it should be text area

* [TRIVIAL] Add npm script for issue creation

* Adjust script & add changeset

* Use cline repo

* remove comment

* open should work on any platform
2025-05-06 13:13:20 +05:30
Trevor Hudson 062bb5bb64 Trevhud/telemetry optimization (#3263)
* add collection method

* collect messages

* changeset

* remove commented out parts

* remove check to send events anytime a new task is created while on an existing task

* Update src/core/controller/task/clearTask.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Update src/services/telemetry/TelemetryService.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Lower border radius

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
Co-authored-by: Ara <arafat.da.khan@gmail.com>
2025-05-06 10:52:20 +05:30
Peter Dave Hello b667224c13 Extend ReasoningEffort to non-o3-mini reasoning models for all providers (#3036)
It's somehow locked to o3-mini for some providers, and the description,
should be updated for all OpenAI o series reasoning models.
2025-05-06 10:25:10 +05:30
Evan ffbafab5e2 Migrate prompting folder new docs (#3254)
* migrate prompting section

* changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@mac.mynetworksettings.com>
Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-05 21:07:30 -07:00
Peter Dave Hello 3e9c83b99d Add the o4-mini model in the isOminiModel (#3035) 2025-05-05 20:58:58 -07:00
canvrno 9eea9d04b5 getRelativePaths protobus migration (#3259) 2025-05-05 20:47:06 -07:00
canvrno c83957660a [PROTOBUS] Move ruleFile conversions to /file/ (#3262)
* v3.14.0 Release Notes

* v3.14.0 Release Notes

* move rule file conversions

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-05-05 19:05:02 -07:00
canvrno cb7234f967 [PROTOBUS] Move deleteTasksWithIds to protobus (#3282)
* deleteTasksWithIDs protobus migration

* Moved deleteTasksWithIds to dedicated message type

* Created common StringArrayRequest

* Delete webview-ui/.vite-port
2025-05-05 19:03:27 -07:00
Frostbourne a953f6e768 Add confirmation dialog to Delete All History (#3316)
* delete all confirmation dialog

* changeset

* Use showWarningMessage instead

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-05 14:55:18 -07:00
Evan 8516aabb88 Migrate getting started new docs (#3252)
* migrate getting-started to new docs

* changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@mac.mynetworksettings.com>
Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-05 16:15:32 -05:00
Ara e963d2c194 Introducing Quote a Message in Chat (#3223)
* Adding double click support

* Adding double click support

* Adding double click support

* Adding double click support

* Adding double click support

* Adding double click support

* Adding double click support

* Adding double click support

* Adding double click support

* Adding double click support

* Adding double click support

* Adding double click support

* Cleanup

* Working better

* Working better

* Working better

* add markdown

* add markdown

* add markdown

* add markdown

* add markdown

* Lower border radius

* Lower border radius

* Delete webview-ui/.vite-port

---------

Co-authored-by: Frostbourne <frostbournesb@protonmail.com>
2025-05-06 02:44:19 +05:30
Derek Lopes 3b0dbd304a bugfix: AWS credentials overridden by AWS_PROFILE env variable in shell init scripts (#2888) 2025-05-05 16:03:09 -05:00
Toshii 274349f944 add ui component for external rules files (#3291)
* base

* svg

* delete refresh

* changeset
2025-05-05 09:49:35 -05:00
Frostbourne 6d24e22bf6 Make previous updates a dropdown (#3265)
* Add Dropdown for previous updates

* changeset
2025-05-04 17:25:16 -07:00
Frostbourne 8fae4e64d5 Allow for multiple dev server instances (#3288)
* Allow multiple dev servers at once

* logs

* fix portFilePath

* improve log

* default port fallback

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-04 17:24:37 -07:00
Toshii fc5adcf8eb add open ai cache pricing & check to ui (#3268)
* base

* changeset

* Update src/core/controller/index.ts

Co-authored-by: Ara <arafat.da.khan@gmail.com>

---------

Co-authored-by: Ara <arafat.da.khan@gmail.com>
2025-05-04 12:16:46 -07:00
196 changed files with 11407 additions and 1579 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Add the o4-mini model in the isOminiModel
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Allow option to collect events to send them in a bundle to avoid sending too many events
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
add open ai cache to ui
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
disable autocapture
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Update deployer team name
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Moved rule file conversions
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
suggested model exists again
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
getRelativePaths protobus migration
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
getOllamaModels protobus migration
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Add FeatureFlagProvider service for the Node.js extension side
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
added copy buttons to task header and assistant messages
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Increasing file size that can be read by cline
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Add org to team affiliation check
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
fix-bedrock-api
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Add confirmation dialog to Delete All History button
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
breakpoint just in system prompt for gemini for OR and cline provider
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix for markdown copy excessive escape characters
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
fetch cache details from generation endpoint
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Bump ollama from 0.5.13 to 0.5.15
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Add npm script for issue creation
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Migrate more info section to new docs
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Only initialize posthog in the webview if the user has opted into telemetry
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Extend ReasoningEffort to non-o3-mini reasoning models for all providers
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Re-enable tests in workflow
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
requestVsCodeLmModels protobus migration
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Allow the user to form their next message while Cline is taking action
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Adding mistral medium-3 model
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
searchFiles protobus migration
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Add ability to generate commit message via cline
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
updated OR/cline provider to automate gemini models caching
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Add Task Favorites and several proto messages related to tasks
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
getLmStudioModels protobus migration
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
adding quote reply support
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Add enterprise section to new docs
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Raise Errors when users try to upload images larger than 7500x7500 pixels
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Make Previous Updates in the Announcement a dropdown
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Migrate prompting section to new docs
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Migrate running models locally section to new docs
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
timestamp visualization
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Allow the user to scroll when Cline is editing a file by disabling auto-scroll when the user scrolls up
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Add image links to docs
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Migrate MCP section to new docs
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Migrate custom model config section to new docs
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fixed an issue where loading never finished when using an application inference profile for the model ID
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Add support for Gemini Implicit Caching
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Migrate getting-started section to new docs
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Task Timeline
+8
View File
@@ -47,6 +47,14 @@ body:
placeholder: "e.g., Windows 11, macOS Sonoma, Ubuntu 22.04"
validations:
required: true
- type: textarea
id: system-info
attributes:
label: System Info
description: What system information is relevant to the issue?
placeholder: "e.g., CPU: Intel Core i7-11700K, GPU: NVIDIA GeForce RTX 3070, RAM: 32GB DDR4"
validations:
required: true
- type: input
id: cline-version
attributes:
@@ -33,6 +33,7 @@ jobs:
uses: morfien101/actions-authorized-user@4a3cfbf0bcb3cafe4a71710a278920c5d94bb38b
with:
username: ${{ github.actor }}
org: ${{ github.repository_owner }}
team: "deployer"
github_token: ${{ secrets.GITHUB_TOKEN }}
+4
View File
@@ -1,5 +1,9 @@
# Changelog
## [3.14.1]
- Disables autocaptures when initializing feature flags
## [3.14.0]
- Add support for custom model ID in AWS Bedrock provider, enabling use of Application Inference Profile (Thanks @clicube!)
@@ -0,0 +1,121 @@
---
title: "AWS Bedrock"
description: "Learn how to set up AWS Bedrock with Cline using credentials authentication. This guide covers AWS environment setup, regional access verification, and secure integration with the Cline VS Code extension."
---
### Overview
- **AWS Bedrock:** A fully managed service that offers access to leading generative AI models (e.g., Anthropic Claude, Amazon Titan) through AWS.\
[Learn more about AWS Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html).
- **Cline:** A VS Code extension that acts as a coding assistant by integrating with AI models—empowering developers to generate code, debug, and analyze data.
- **Enterprise Focus:** This guide is tailored for organizations with established AWS environments (using IAM roles, AWS SSO, AWS Organizations, etc.) to ensure secure and compliant usage.
---
### Step 1: Prepare Your AWS Environment
#### 1.1 Create or Use an IAM Role/User
1. **Sign in to the AWS Management Console:**\
[AWS Console](https://aws.amazon.com/console/)
2. **Access IAM:**
- Search for **IAM (Identity and Access Management)** in the AWS Console.
- Either create a new IAM user or use your enterprise's AWS SSO to assume a dedicated role for Bedrock access.
- [AWS IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)
#### 1.2 Attach the Required Policies
1. **Attach the Managed Policy:**
- Attach the **`AmazonBedrockFullAccess`** managed policy to your user/role.\
[View AmazonBedrockFullAccess Policy Details](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html)
2. **Confirm Additional Permissions:**
- Ensure your policy includes permissions for model invocation (e.g., `bedrock:InvokeModel` and `bedrock:InvokeModelWithResponseStream`), model listing, and AWS Marketplace actions (like `aws-marketplace:Subscribe`).
- _Enterprise Tip:_ Apply least-privilege practices by scoping resource ARNs and using [Service Control Policies (SCPs)](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) to restrict access where necessary.
---
### Step 2: Verify Regional and Model Access
#### 2.1 Choose and Confirm a Region
1. **Select a Region:**\
AWS Bedrock is available in multiple regions (e.g., US East, Europe, Asia Pacific). Choose the region that meets your latency and compliance needs.\
[AWS Global Infrastructure](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/)
2. **Verify Model Access:**
- In the AWS Bedrock console, confirm that the models your team requires (e.g., Anthropic Claude, Amazon Titan) are marked as "Access granted."
- **Note:** Some advanced models might require an [Inference Profile](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-prereq.html) if not available on-demand.
#### 2.2 Set Up AWS Marketplace Subscriptions (if needed)
1. **Subscribe to Third-Party Models:**
- Navigate to the AWS Bedrock console and locate the model subscription section.
- For models from third-party providers (e.g., Anthropic), accept the terms to subscribe.
- [AWS Marketplace](https://aws.amazon.com/marketplace/)
2. **Enterprise Tip:**
- Model subscriptions are often managed centrally. Confirm with your cloud team if a standard subscription process is in place.
---
### Step 3: Configure the Cline VS Code Extension
#### 3.1 Install and Open Cline
1. **Install VS Code:**\
Download from the [VS Code website](https://code.visualstudio.com/).
2. **Install the Cline Extension:**
- Open VS Code.
- Go to the Extensions Marketplace (`Ctrl+Shift+X` or `Cmd+Shift+X`).
- Search for **Cline** and install it.
#### 3.2 Configure Cline Settings
1. **Open Cline Settings:**
- Click on the settings ⚙️ to select your API Provider.
2. **Select AWS Bedrock as the API Provider:**
- From the API Provider dropdown, choose **AWS Bedrock**.
3. **Enter Your AWS Credentials:**
- Input your **Access Key** and **Secret Key** (or use temporary credentials if using AWS SSO).
- Specify the correct **AWS Region** (e.g., `us-east-1` or your enterprise-approved region).
4. **Select a Model:**
- Choose an on-demand model (e.g., **anthropic.claude-3-5-sonnet-20241022-v2:0**).
5. **Save and Test:**
- Click **Done/Save** to apply your settings.
- Test the integration by sending a simple prompt (e.g., "Generate a Python function to check if a number is prime.").
---
### Step 4: Security, Monitoring, and Best Practices
1. **Secure Access:**
- Prefer AWS SSO/federated roles over long-lived IAM credentials.
- [AWS IAM Best Practices](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)
2. **Enhance Network Security:**
- Consider setting up [AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-services-overview.html) to securely connect to Bedrock.
3. **Monitor and Log Activity:**
- Enable AWS CloudTrail to log Bedrock API calls.
- Use CloudWatch to monitor metrics like invocation count, latency, and token usage.
- Set up alerts for abnormal activity.
4. **Handle Errors and Manage Costs:**
- Implement exponential backoff for throttling errors.
- Use AWS Cost Explorer and set billing alerts to track usage.\
[AWS Cost Management](https://docs.aws.amazon.com/cost-management/latest/userguide/what-is-aws-cost-management.html)
5. **Regular Audits and Compliance:**
- Periodically review IAM roles and CloudTrail logs.
- Follow internal data privacy and governance policies.
---
### Conclusion
By following these steps, your enterprise team can securely integrate AWS Bedrock with the Cline VS Code extension to accelerate development:
1. **Prepare Your AWS Environment:** Create or use a secure IAM role/user, attach the `AmazonBedrockFullAccess` policy, and ensure necessary permissions.
2. **Verify Region and Model Access:** Confirm that your selected region supports your required models and subscribe via AWS Marketplace if needed.
3. **Configure Cline in VS Code:** Install and set up Cline with your AWS credentials and choose an appropriate model.
4. **Implement Security and Monitoring:** Use best practices for IAM, network security, monitoring, and cost management.
For further details, consult the [AWS Bedrock Documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) and coordinate with your internal cloud team. Happy coding!
---
_This guide will be updated as AWS Bedrock and Cline evolve. Always refer to the latest documentation and internal policies for up-to-date practices._
@@ -0,0 +1,42 @@
---
title: "AWS Bedrock w/ Profile Authentication"
description: "Learn how to configure AWS Bedrock to use AWS Profiles for authentication with Cline, focusing on SSO/Federated roles for secure access."
---
### Overview
Cline offers the option of utilizing AWS credentials or AWS profiles to access AWS Bedrock services. SSO/Federated roles are suggested over Legacy IAM configuration; this guide describes how to configure your environment so that Cline uses SSO roles for authentication.
---
### Configuration Steps
1. Install the [latest version](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) of AWS CLI
- Follow the AWS docs to install your OS-specific version of AWS CLI
2. [Configure IAM authentication](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html) with the AWS CLI
- If you do not already have AWS access through the IAM Identity Center, follow the [IAM User Guide](https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html) to set up IAM users and roles. Ensure you have a `PowerUserAccess` role.
- If you have access to AWS through your employer, open your AWS access portal and find the appropriate account. Ensure you have `PowerUserAccess` permissions.
- Open the `Access keys` link and note the `SSO start URL` and `SSO region`, which are needed in the next step
3. Continue configuring your profile using [the `aws configure sso` CLI wizard](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html#cli-configure-sso-configure)
- Once configured, use the following command to authenticate the AWS CLI: `aws sso login --profile <AWS-profile-name>`
- Note which profile name you attach to your AWS account, this is needed to configure Cline in the following steps
4. If you haven't already done so, install VSCode and the Cline extension. Consult the [Getting Started](/getting-started) page for guidance.
5. Open the Cline extension, then click on the settings button ⚙️ to select your API Provider.
- From the API Provider dropdown, select AWS Bedrock
- Select the AWS Profile radio button, then enter the AWS Profile Name from step 3
- Select your AWS Region from the dropdown menu
- Selecting the cross-region inference checkbox is required for some models
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/cline-aws-setup-markup%20(1).png"
alt="AWS Bedrock configuration in Cline settings showing profile authentication setup"
/>
</Frame>
+209
View File
@@ -0,0 +1,209 @@
---
title: "GCP Vertex AI"
description: "Configure GCP Vertex AI with Cline to access leading generative AI models like Claude 3.5 Sonnet v2. This guide covers GCP environment setup, authentication, and secure integration for enterprise teams."
---
### Overview
**GCP Vertex AI:**\
A fully managed service that provides access to leading generative AI models—such as Anthropic's Claude 3.5 Sonnet v2—through Google Cloud.\
[Learn more about GCP Vertex AI](https://cloud.google.com/vertex-ai).
This guide is tailored for organizations with established GCP environments (leveraging IAM roles, service accounts, and best practices in resource management) to ensure secure and compliant usage.
---
### Step 1: Prepare Your GCP Environment
#### 1.1 Create or Use a GCP Project
- **Sign in to the GCP Console:**\
[Google Cloud Console](https://console.cloud.google.com/)
- **Select or Create a Project:**\
Use an existing project or create a new one dedicated to Vertex AI.
#### 1.2 Set Up IAM Permissions and Service Accounts
- **Assign Required Roles:**
- Grant your user (or service account) the **Vertex AI User** role (`roles/aiplatform.user`)
- For service accounts, also attach the **Vertex AI Service Agent** role (`roles/aiplatform.serviceAgent`) to enable certain operations
- Consider additional predefined roles as needed:
- Vertex AI Platform Express Admin
- Vertex AI Platform Express User
- Vertex AI Migration Service User
- **Cross-Project Resource Access:**
- For BigQuery tables in different projects, assign the **BigQuery Data Viewer** role
- For Cloud Storage buckets in different projects, assign the **Storage Object Viewer** role
- For external data sources, refer to the [GCP Vertex AI Access Control documentation](https://cloud.google.com/vertex-ai/docs/general/access-control)
---
### Step 2: Verify Regional and Model Access
#### 2.1 Choose and Confirm a Region
Vertex AI supports eight regions. Select a region that meets your latency, compliance, and capacity needs. Examples include:
- **us-east5 (Columbus, Ohio)**
- **us-east1 (South Carolina)**
- **us-east4 (Northern Virginia)**
- **us-central1 (Iowa)**
- **us-west1 (The Dalles, Oregon)**
- **us-west4 (Las Vegas, Nevada)**
- **europe-west1 (Belgium)**
- **asia-southeast1 (Singapore)**
#### 2.2 Enable the Claude 3.5 Sonnet v2 Model
- **Open Vertex AI Model Garden:**\
In the Cloud Console, navigate to **Vertex AI → Model Garden**
- **Enable Claude 3.5 Sonnet v2:**\
Locate the model card for Claude 3.5 Sonnet v2 and click **Enable**
---
### Step 3: Configure the Cline VS Code Extension
#### 3.1 Install and Open Cline
- **Download VS Code:**\
[Download Visual Studio Code](https://code.visualstudio.com/)
- **Install the Cline Extension:**
- Open VS Code
- Navigate to the Extensions Marketplace (Ctrl+Shift+X or Cmd+Shift+X)
- Search for **Cline** and install the extension
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/cline-extension-arrow.png"
alt="Cline extension in VS Code"
/>
</Frame>
#### 3.2 Configure Cline Settings
- **Open Cline Settings:**\
Click the settings ⚙️ icon within the Cline extension
- **Set API Provider:**\
Choose **GCP Vertex AI** from the API Provider dropdown
- **Enter Your Google Cloud Project ID:**\
Provide the project ID you set up earlier
- **Select the Region:**\
Choose one of the supported regions (e.g., `us-east5`)
- **Select the Model:**\
From the available list, choose **Claude 3.5 Sonnet v2**
- **Save and Test:**\
Save your settings and test by sending a simple prompt (e.g., "Generate a Python function to check if a number is prime.")
---
### Step 4: Authentication and Credentials Setup
#### Option A: Using Your Google Account (User Credentials)
1. **Install the Google Cloud CLI:**\
Follow the [installation guide](https://cloud.google.com/sdk/docs/install)
2. **Initialize and Authenticate:**
```bash
gcloud init
gcloud auth application-default login
```
- This sets up Application Default Credentials (ADC) using your Google account
3. **Restart VS Code:**\
Ensure VS Code is restarted so that the Cline extension picks up the new credentials
#### Option B: Using a Service Account (JSON Key)
1. **Create a Service Account:**
- In the GCP Console, navigate to **IAM & Admin > Service Accounts**
- Create a new service account (e.g., "vertex-ai-client")
2. **Assign Roles:**
- Attach **Vertex AI User** (`roles/aiplatform.user`)
- Attach **Vertex AI Service Agent** (`roles/aiplatform.serviceAgent`)
- Optionally, add other roles as required
3. **Generate a JSON Key:**
- In the Service Accounts section, manage keys for your service account and download the JSON key
4. **Set the Environment Variable:**
```bash
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account-key.json"
```
- This instructs Google Cloud client libraries (and Cline) to use this key
5. **Restart VS Code:**\
Launch VS Code from a terminal where the `GOOGLE_APPLICATION_CREDENTIALS` variable is set
---
### Step 5: Security, Monitoring, and Best Practices
#### 5.1 Enforce Least Privilege
- **Principle of Least Privilege:**\
Only grant the minimum necessary permissions. Custom roles can offer finer control compared to broad predefined roles
- **Best Practices:**\
Refer to [GCP IAM Best Practices](https://cloud.google.com/iam/docs/best-practices)
#### 5.2 Manage Resource Access
- **Project vs. Resource-Level Access:**\
Access can be managed at both levels. Note that resource-level permissions (e.g., for BigQuery or Cloud Storage) add to, but do not override, project-level policies
#### 5.3 Monitor Usage and Quotas
- **Model Observability Dashboard:**
- In the Vertex AI Console, navigate to the **Model Observability** dashboard
- Monitor metrics such as request throughput, latency, and error rates (including 429 quota errors)
- **Quota Management:**
- If you encounter 429 errors, check the **IAM & Admin > Quotas** page
- Request a quota increase if necessary\
[Learn more about GCP Vertex AI Quotas](https://cloud.google.com/vertex-ai/docs/quotas)
#### 5.4 Service Agents and Cross-Project Considerations
- **Service Agents:**\
Be aware of the different service agents:
- Vertex AI Service Agent
- Vertex AI RAG Data Service Agent
- Vertex AI Custom Code Service Agent
- Vertex AI Extension Service Agent
- **Cross-Project Access:**\
For resources in other projects (e.g., BigQuery, Cloud Storage), ensure that the appropriate roles (BigQuery Data Viewer, Storage Object Viewer) are assigned
---
### Conclusion
By following these steps, your enterprise team can securely integrate GCP Vertex AI with the Cline VS Code extension to harness the power of **Claude 3.5 Sonnet v2**:
- **Prepare Your GCP Environment:**\
Create or use a project, configure IAM with least privilege, and ensure necessary roles (including the Vertex AI Service Agent role) are attached
- **Verify Regional and Model Access:**\
Confirm that your chosen region supports Claude 3.5 Sonnet v2 and that the model is enabled
- **Configure Cline in VS Code:**\
Install Cline, enter your project ID, select the appropriate region, and choose the model
- **Set Up Authentication:**\
Use either user credentials (via `gcloud auth application-default login`) or a service account with a JSON key
- **Implement Security and Monitoring:**\
Adhere to best practices for IAM, manage resource access carefully, and monitor usage with the Model Observability dashboard
For further details, please consult the [GCP Vertex AI Documentation](https://cloud.google.com/vertex-ai/docs) and your internal security policies.\
Happy coding!
_This guide will be updated as GCP Vertex AI and Cline evolve. Always refer to the latest documentation for current practices._
@@ -0,0 +1,65 @@
---
title: "LiteLLM & Cline (using Codestral)"
description: "Learn how to set up and run LiteLLM with Cline using the Codestral model. This guide covers Docker setup, configuration, and integration with Cline."
---
### Using LiteLLM with Cline
This guide demonstrates how to run a demo for LiteLLM starting with the Codestral model for use with Cline.
#### Prerequisites
- [Docker CLI or Docker Desktop](https://www.docker.com/get-started/) installed to run the LiteLLM image locally
- For this example config: A Codestral API Key (different from the Mistral API Keys)
#### Setup
1. **Create a `.env` file and fill in the appropriate field**
```bash
# Tip: Use the following command to generate a random alphanumeric key:
# openssl rand -base64 32 | tr -dc 'A-Za-z0-9' | head -c 32
LITELLM_MASTER_KEY=YOUR_LITELLM_MASTER_KEY
CODESTRAL_API_KEY=YOUR_CODESTRAL_API_KEY
```
_Note: Although this is limited to localhost, it's a good practice set LITELLM_MASTER_KEY to something secure_
2. **Configuration**
We'll need to create a `config.yaml` file to contain our LiteLLM configuration. In this case we'll just have one model, 'codestral-latest' and label it 'codestral'
```yaml
model_list:
- model_name: codestral
litellm_params:
model: codestral/codestral-latest
api_key: os.environ/CODESTRAL_API_KEY
```
#### Running the Demo
1. **Startup the LiteLLM docker container**
```bash
docker run \
--env-file .env \
-v $(pwd)/config.yaml:/app/config.yaml \
-p 127.0.0.1:4000:4000 \
ghcr.io/berriai/litellm:main-latest \
--config /app/config.yaml --detailed_debug
```
2. **Setup Cline**
Once the LiteLLM server is up and running you can set it up in Cline:
- Base URL should be `http://0.0.0.0:4000/v1`
- API Key should be the one you set in `.env` for LITELLM_MASTER_KEY
- Model ID is `codestral` or whatever you named it under `config.yaml`
#### Getting Help
- [LiteLLM Documentation](https://docs.litellm.ai/)
- [Mistral AI Console](https://console.mistral.ai/)
- [Cline Discord Community](https://discord.gg/cline)
+59
View File
@@ -54,6 +54,23 @@
},
"navigation": {
"groups": [
{
"group": "Getting Started",
"pages": [
"getting-started/for-new-coders",
"getting-started/installing-cline",
"getting-started/installing-dev-essentials",
"getting-started/model-selection-guide",
"getting-started/our-favorite-tech-stack",
"getting-started/task-management",
"getting-started/understanding-context-management",
"getting-started/what-is-cline"
]
},
{
"group": "Improving Your Prompting Skills",
"pages": ["prompting/prompt-engineering-guide", "prompting/cline-memory-bank"]
},
{
"group": "Exploring Cline's Tools",
"pages": [
@@ -64,6 +81,48 @@
"exploring-clines-tools/remote-browser-support",
"exploring-clines-tools/slash-commands"
]
},
{
"group": "Enterprise Solutions",
"pages": [
"enterprise-solutions/cloud-provider-integration",
"enterprise-solutions/custom-instructions",
"enterprise-solutions/mcp-servers",
"enterprise-solutions/security-concerns"
]
},
{
"group": "MCP Servers",
"pages": [
"mcp/mcp-overview",
"mcp/adding-mcp-servers-from-github",
"mcp/configuring-mcp-servers",
"mcp/connecting-to-a-remote-server",
"mcp/mcp-marketplace",
"mcp/mcp-server-development-protocol",
"mcp/mcp-transport-mechanisms"
]
},
{
"group": "Custom Model Configurations",
"pages": [
"custom-model-configs/aws-bedrock-with-credentials-authentication",
"custom-model-configs/aws-bedrock-with-profile-authentication",
"custom-model-configs/gcp-vertex-ai",
"custom-model-configs/litellm-and-cline-using-codestral"
]
},
{
"group": "Running Models Locally",
"pages": [
"running-models-locally/read-me-first",
"running-models-locally/lm-studio",
"running-models-locally/ollama"
]
},
{
"group": "More Info",
"pages": ["more-info/telemetry"]
}
]
},
@@ -0,0 +1,39 @@
---
title: "Cloud Provider Integration"
---
Cline supports major cloud providers like AWS Bedrock and Google's Cloud Vertex; whichever your team currently uses is appropriate, and there's no need to change providers to utilize Cline's features.
For the purpose of this document, we assume your organization will use cloud-based frontier models. Cloud inference providers offer cutting-edge capabilities and the flexibility to select models which best suit your needs.
Certain scenarios may warrant using local models, including handling highly sensitive data, applications requiring consistent low-latency responses, or compliance with strict data sovereignty requirements. If your team needs to utilize local models, see [Running Local Models ](/running-models-locally/read-me-first.mdx)with Cline.
---
## AWS Bedrock Setup Guides
#### [IAM Security Best Practices](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) (For administrators)
#### [AWS Bedrock setup for Legacy IAM (AWS Credentials)](/custom-model-configs/aws-bedrock-with-credentials-authentication.mdx)
#### [AWS Bedrock setup for SSO token (AWS Profile)](/custom-model-configs/aws-bedrock-with-profile-authentication.mdx)
#### VPC Endpoint Setup
To protect your team's data, Cline supports VPC (Virtual Private Cloud) endpoints, which create private connections between your data and AWS Bedrock. AWS VPCs enhance security by eliminating the need for public IP addresses, network gateways, or complex firewall rules—essentially creating a private highway for data that bypasses the public internet entirely. By keeping traffic within AWS's private network, teams also benefit from lower latency and more predictable performance when accessing services like AWS Bedrock or custom APIs. For those working with confidential information or operating in highly regulated industries like healthcare or finance, VPCs offers the perfect balance between the accessibility of cloud services and the security of private infrastructure.
---
1. Consult the [AWS guide](https://docs.aws.amazon.com/bedrock/latest/userguide/vpc-interface-endpoints.html) to creating VPC endpoints. This document specifies pre-requisites and describes the syntax used for creating VPC endpoints.
2. Follow the directions for [creating a VPC endpoint](https://docs.aws.amazon.com/vpc/latest/privatelink/create-interface-endpoint.html#create-interface-endpoint-aws) in the AWS console. The image below pertains to steps 4 and 5 of the AWS guide linked above.
<Frame>
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/vpc-console.png" alt="VPC Console" />
</Frame>
3. Note the IP address of your VPC endpoint, open Cline's settings menu, and select `AWS Bedrock`from the API Provider dropdown.
4. Click the `Use Custom VPC endpoint`checkbox and enter the IP address of your VPC endpoint
<Frame>
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/vpc-settings-menu.png" alt="VPC Settings Menu" />
</Frame>
@@ -0,0 +1,22 @@
---
title: "Custom Instructions"
---
## Building Custom Instructions for Teams
**Creating standardized project instructions ensures that all team members work within consistent guidelines. Start by documenting your project's technical foundation, then identify which information needs to be included in the instructions. The exact scope will vary depending on your team's needs, but generally it's best to provide as much information as possible. By creating comprehensive instructions that all team members follow, you establish a shared understanding of how code should be written, tested, and deployed across your project, resulting in more maintainable and consistent software.**
---
Here are a few topics and examples to consider for your team's custom instructions:
1. **Testing framework and specific commands**
- "All components must include Jest tests with at least 85% coverage. Run tests using `npm run test:coverage` before submitting any pull request."
2. **Explicit library preferences**
- "Use React Query for data fetching and state management. Avoid Redux unless specifically required for complex global state. For styling, use Tailwind CSS with our custom theme configuration found in `src/styles/theme.js.`"
3. **Where to find documentation**
- "All API documentation is available in our internal Notion workspace under 'Engineering > API Reference'. For component usage examples, refer to our Storybook instance at `https://storybook.internal.company.com`"
4. **Which MCP servers to use, and for which purposes**
- "For database operations, use the Postgres MCP server with credentials stored in 1Password under 'Development > Database'. For deployments, use the AWS MCP server which requires the deployment role from IAM. Refer to `docs/mcp-setup.md` for configuration instructions."
5. **Coding conventions specific to your project**
- "Name all React components using PascalCase and all helper functions using camelCase. Place components in the `src/components` directory organized by feature, not by type. Always use TypeScript interfaces for prop definitions."
+25
View File
@@ -0,0 +1,25 @@
---
title: "MCP Servers"
---
**Model Context Protocol (MCP) servers expand Cline's capabilities by providing standardized access to external data sources and executable functions. By implementing MCP servers, LLM tools can dynamically retrieve and incorporate relevant information from both local and remote data sources. This capability ensures that the models operate with the most current and contextually appropriate data, improving the accuracy and relevance of their outputs.**
---
### Secure Architecture Fundamentals
MCP servers follow a client-server architecture where hosts (LLM applications like Cline) initiate connections through a transport layer to MCP servers. This architecture inherently provides security benefits as it maintains clear separation between components. Enterprise deployments should focus on the proper implementation of this architecture to ensure secure operations, particularly regarding the message exchange patterns and connection lifecycle management. For MCP architecture details, see [MCP Architecture](https://modelcontextprotocol.io/docs/concepts/architecture), and for latest specifications, see [MCP Specifications](https://spec.modelcontextprotocol.io/specification/2024-11-05/).
### Transport Layer Security
For enterprise environments, selecting the appropriate transport mechanism is crucial. While stdio transport works efficiently for local processes, HTTP with Server-Sent Events (SSE) transport requires additional security measures. TLS should be used for all remote connections whenever possible. This is especially important when MCP servers are deployed across different network segments within corporate infrastructure.
### Message Validation and Access Control
The MCP architecture defines standard error codes and message types (Requests, Results, Errors, and Notifications), providing a structured framework for secure communication. Security teams should consider message validation, sanitizing inputs, checking message size limits, and verifying JSON-RPC format. Additionally, implementing resource protection through access controls, path validation, and request rate limiting helps prevent potential abuse of MCP server capabilities.
### Monitoring and Compliance
For enterprise compliance requirements, implementing comprehensive logging of protocol events, message flows, and errors is essential. The MCP architecture supports diagnostic capabilities including health checks, connection state monitoring, and resource usage tracking. Organizations should extend these capabilities to meet their specific compliance needs, particularly for audit trails of all MCP server interactions and resource access patterns.
By leveraging the client-server design of the MCP architecture and implementing appropriate security controls at each layer, enterprises can safely integrate MCP servers into their environments while maintaining their security posture and meeting regulatory requirements.
@@ -0,0 +1,63 @@
---
title: "Security Concerns"
---
## Enterprise Security with Cline
#### Cline addresses enterprise security concerns through its unique client-side architecture that prioritizes data privacy, secure cloud integration, and transparent operations. Below is a comprehensive overview of how Cline maintains robust security measures for enterprise environments.
---
### Client-Side Architecture
Cline operates exclusively as a client-side VSCode extension with zero server-side components. This fundamental design choice ensures that your code and data remain within your secure environment at all times. Unlike traditional AI assistants that send data to external servers for processing, Cline connects directly to your chosen cloud provider's AI endpoints, keeping all sensitive information within your infrastructure boundaries.
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/cline-arch.png"
alt="Cline's relationship to local and remote assets"
/>
</Frame>
### Data Privacy Commitment
Cline implements a strict zero data retention policy, meaning your intellectual property never leaves your secure environment. The extension does not collect, store, or transmit your code to any central servers. This approach significantly reduces potential attack vectors that might otherwise be introduced through data transmission to third-party systems. Telemetry collection is optional and requires explicit consent.
### Cloud Provider Integration
Enterprise teams can access cutting-edge AI models through their existing cloud deployments. Cline supports seamless integration with:
- AWS Bedrock
- Google Cloud Vertex AI
- Microsoft Azure
These integrations utilize your organization's existing security credentials, including native IAM role assumption for AWS. This ensures that all AI processing occurs within your corporate cloud environment, maintaining compliance with your established security protocols.
### Open-Source Transparency
Cline's codebase is completely open-source, allowing for comprehensive security auditing by your internal teams. This transparency enables security professionals to verify exactly how the extension functions and confirm that it adheres to your organization's security requirements. Organizations can review the code to ensure it aligns with their security policies before deployment.
### Controlled Modifications
The extension implements safeguards against unauthorized changes to your codebase. Cline requires explicit user approval for all file modifications and terminal commands, preventing accidental or unwanted alterations. This approval-based workflow maintains the integrity of your projects while still providing AI assistance.
### Enterprise Deployment Support
For organizations with strict security review processes, Cline provides comprehensive documentation including detailed deployment diagrams, sequence diagrams illustrating all data flows, and complete security posture documentation. These materials facilitate thorough security reviews and help demonstrate compliance with enterprise data handling standards and regulations.
### Access Control
Enterprise editions of Cline (planned for Q2 2025) will include centralized administration features that allow organizations to:
- Manage user access with customizable permission levels
- Provision accounts with corporate credentials
- Immediately revoke access when needed
- Control which AI providers and LLM endpoints can be used
- Deploy standardized settings across the organization
- Prevent unauthorized use of personal API keys
### Compliance and Governance
Cline's architecture supports compliance with data sovereignty requirements and enterprise data handling regulations. The planned Enterprise Complete edition will further enhance governance with detailed audit logging, compliance reporting, and automated policy enforcement mechanisms.
By combining client-side processing, direct cloud provider integration, and transparent operations, Cline offers enterprise teams a secure way to leverage AI assistance while maintaining strict control over their sensitive code and data.
+9 -3
View File
@@ -28,7 +28,10 @@ After each tool use, you can:
2. Click the "Restore" button to open restore options
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Checkpoint comparison and restore options" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(13).png"
alt="Checkpoint comparison and restore options"
/>
</Frame>
#### Rolling Back
@@ -60,7 +63,7 @@ Checkpoints let you be more experimental with Cline. While human coding is often
- Ideal for exploring different design patterns or architectural approaches
<Frame caption="In this case, I didn't like the changes Cline made to my robot dog-walking website (still working on the robots) and I wanted to revert both the codebase and the task to before any changes were made so I could start fresh.">
<img src="/assets/robot_panel_dark.png" alt="Checkpoint restore demo" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/checkpointsDemo.gif" alt="Checkpoint restore demo" />
</Frame>
### ✨ Best Practices
@@ -104,5 +107,8 @@ Perhaps you didn't get the results you wanted, thought of a better way to phrase
- Shift + Enter: Insert new line / line break
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Message editing interface" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/message-editing.png"
alt="Message editing interface"
/>
</Frame>
@@ -7,7 +7,10 @@ title: "Plan & Act Modes: A Guide to Effective AI Development"
Plan & Act modes represent Cline's approach to structured AI development, emphasizing thoughtful planning before implementation. This dual-mode system helps developers create more maintainable, accurate code while reducing iteration time.
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Use Plan to gather context before using Act to implement the plan" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/planningThenActing%20(1).gif"
alt="Use Plan to gather context before using Act to implement the plan"
/>
</Frame>
### Understanding the Modes
@@ -27,7 +30,7 @@ Plan & Act modes represent Cline's approach to structured AI development, emphas
- Can execute changes to your codebase
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Act mode capabilities" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(5).png" alt="Act mode capabilities" />
</Frame>
### Workflow Guide
@@ -39,7 +42,7 @@ Begin every significant development task in Plan mode:
In this mode:
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Plan mode workflow" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(5)%20(1).png" alt="Plan mode workflow" />
</Frame>
- Share your requirements
@@ -48,7 +51,10 @@ In this mode:
- Develop implementation strategy
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Planning phase" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(2)%20(1)%20(1)%20(1).png"
alt="Planning phase"
/>
</Frame>
#### 2. Switch to Act Mode
@@ -56,7 +62,7 @@ In this mode:
Once you have a clear plan, switch to Act mode:
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Switching to Act mode" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/switching-to-act.gif" alt="Switching to Act mode" />
</Frame>
Act mode allows Cline to:
@@ -90,7 +96,10 @@ Complex projects often require multiple plan-act cycles:
4. Document significant decisions
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Implementation best practices" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(3)%20(1).png"
alt="Implementation best practices"
/>
</Frame>
### Power User Tips
@@ -119,7 +128,7 @@ Complex projects often require multiple plan-act cycles:
- Executing test cases
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Mode usage patterns" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(6).png" alt="Mode usage patterns" />
</Frame>
### Contributing
+68
View File
@@ -0,0 +1,68 @@
---
title: "For New Coders"
description: "Welcome to Cline, your AI-powered coding companion! This guide will help you quickly set up your development environment and begin your coding journey with ease."
---
> 💡 **Tip:** If you're completely new to coding, take your time with each step. There's no rush — Cline is here to guide you!
### 🚀 Getting Started
Before you jump into coding, make sure you have these essentials ready:
#### 1. **VS Code**
A popular, free, and powerful code editor.
- [Download VS Code](https://code.visualstudio.com/)
📺 **Recommended YouTube Tutorial:** [How to Install VS Code](https://www.youtube.com/watch?v=MlIzFUI1QGA)
> ✅ **Pro Tip:** Install VS Code in your Applications folder (macOS) or Program Files (Windows) for easy access from your dock or start menu.
#### 2. **Essential Development Tools**
Basic software required for coding efficiently:
- Homebrew (macOS)
- Node.js
- Git
👉 Follow our detailed guide on Installing Essential Development Tools with step-by-step help from Cline.
📺 **Recommended YouTube Tutorials:**
- **For macOS:**
- [Install Homebrew on Mac](https://www.youtube.com/watch?v=hwGNgVbqasc)
- [Install Git on MacOS 2024](https://www.youtube.com/watch?v=B4qsvQ5IqWk)
- [Install Node.js on Mac (M1 | M2 | M3)](https://www.youtube.com/watch?v=I8H4wolRFBk)
- **For Windows:**
- [Install Git on Windows 10/11 (2024)](https://www.youtube.com/watch?v=yjxv1HuRQy0)
- [Install Node.js in Windows 10/11](https://www.youtube.com/watch?v=uCgAuOYpJd0)
> ⚠️ **Note:** If you run into permission issues during installation, try running your terminal or command prompt as an administrator.
#### 3. **Organize Your Projects**
Create a dedicated folder named `Cline` in your Documents folder for all your coding projects:
- **macOS:** `/Users/[your-username]/Documents/Cline`
- **Windows:** `C:\Users\[your-username]\Documents\Cline`
Inside your `Cline` folder, structure projects clearly:
- `Documents/Cline/workout-app` _(e.g., for a fitness tracking app)_
- `Documents/Cline/portfolio-website` _(e.g., to showcase your work)_
> 💡 **Tip:** Keeping your projects organized from the start will save you time and confusion later!
#### 4. **Install the Cline VS Code Extension**
Enhance your coding workflow by installing the Cline extension directly within VS Code:
- Get Started with Cline Extension Tutorial
📺 **Recommended YouTube Tutorial:** [How To Install Extensions in VS Code](https://www.youtube.com/watch?v=E7trgwZa-mk)
> ✅ **Pro Tip:** After installing, reload VS Code to ensure the extension is activated properly.
🎉 You're all set! Dive in and start coding smarter and faster with **Cline**.
+84
View File
@@ -0,0 +1,84 @@
---
title: "Installing Cline"
description: "Cline is a VS Code extension that brings AI-powered coding assistance directly
to your editor. Install using one of these methods:"
---
### Installation Options
- **VS Code Marketplace (Recommended):** Fastest method for standard VS Code and Cursor users.
- **Open VSX Registry:** For VS Code-compatible editors like VSCodium.
### 🛠️ VS Code Marketplace: Step-by-Step Setup
Follow these steps to get Cline up and running:
1. **Open VS Code:** Launch the VS Code application.
> ⚠️ **Note:** If VS Code shows "Running extensions might...", click "Allow".
2. **Open Your Cline Folder:** In VS Code, open the Cline folder you created in Documents.
3. **Navigate to Extensions:** Click on the Extensions icon in the Activity Bar on the side of VS Code (`Ctrl + Shift + X` or `Cmd + Shift + X`).
4. **Search for 'Cline':** In the Extensions search bar, type `Cline`.
<Frame caption="VS Code marketplace with Cline extension ready to install">
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(20).png"
alt="VS Code marketplace showing Cline extension"
/>
</Frame>
1. **Install the Extension:** Click the "Install" button next to the Cline extension.
2. **Open Cline:**
- Click the Cline icon in the Activity Bar.
- Or, use the command palette (`Ctrl/Cmd + Shift + P`) and type "Cline: Open In New Tab" for a better view.
3. **Troubleshooting:** If you don't see the Cline icon, try restarting VS Code.
> ✅ **Pro Tip:** You should see the Cline chat window appear in your VS Code editor!
### 🌐 Open VSX Registry
For VS Code-compatible editors without Marketplace access (like VSCodium and Windsurf):
1. Open your editor.
2. Access the Extensions view.
3. Search for "Cline".
4. Select "Cline" by saoudrizwan and click **Install**.
5. Reload if prompted.
### 👤 Creating Your Cline Account
Now that you have Cline installed, let's get you set up with your account:
1. **Sign In to Cline:**
- Click the **Sign In** button in the Cline extension.
- You'll be taken to [app.cline.bot](https://app.cline.bot) to create your account.
2. **Start with Free Credits:**
- No credit card needed!
3. **Available AI Models:**
- Anthropic Claude 3.5-Sonnet (recommended for coding)
- DeepSeek Chat (cost-effective alternative)
- Google Gemini 2.0 Flash
- And more — all through your Cline account.
4. -
### 💻 Your First Interaction with Cline
You're ready to start building! Copy and paste this prompt into the Cline chat window:
```
Hey Cline! Could you help me create a new project folder called "hello-world" in my Cline directory and make a simple webpage that says "Hello World" in big blue text?
```
> ✅ **Pro Tip:** Cline will help you create the project folder and set up your first webpage!
### 🧩 Tips for Working with Cline
- **Ask Questions:** If you're unsure about something, ask Cline!
- **Use Screenshots:** Cline can understand images — show him what you're working on.
- **Copy and Paste Errors:** Share error messages in the chat for solutions.
- **Speak Plainly:** Use your own words — Cline will translate them into code.
### 🫂 Still Struggling?
Join our Discord community and engage with our team and other Cline users directly.
@@ -0,0 +1,111 @@
---
title: "Installing Dev Essentials"
description: >-
When you start coding, you'll need some essential development tools installed
on your computer. Cline can help you install everything you need in a safe,
guided way.
---
### 🧰 The Essential Tools
Here are the core tools you'll need for development:
- **Node.js & npm:** Required for JavaScript and web development
- **Git:** For tracking changes in your code and collaborating with others
- **Package Managers:** Tools that make it easy to install other development tools
- Homebrew for macOS
- Chocolatey for Windows
- apt/yum for Linux
> 💡 **Tip:** These tools are the foundation of your developer toolkit. Installing them properly will set you up for success!
### 🚀 Let Cline Install Everything
Copy one of these prompts based on your operating system and paste it into **Cline**:
#### For macOS
```
Hello Cline! I need help setting up my Mac for software development. Could you please help me install the essential development tools like Homebrew, Node.js, Git, and any other core utilities that are commonly needed for coding? I'd like you to guide me through the process step-by-step.
```
#### For Windows
```
Hello Cline! I need help setting up my Windows PC for software development. Could you please help me install the essential development tools like Node.js, Git, and any other core utilities that are commonly needed for coding? I'd like you to guide me through the process step-by-step.
```
#### For Linux
```
Hello Cline! I need help setting up my Linux system for software development. Could you please help me install the essential development tools like Node.js, Git, and any other core utilities that are commonly needed for coding? I'd like you to guide me through the process step-by-step.
```
> ✅ **Pro Tip:** Cline will show you each command before running it. You stay in control the entire time!
### 🔍 What Will Happen
Cline will guide you through the following steps:
1. Installing the appropriate package manager for your system
2. Using the package manager to install Node.js and Git
3. Showing you the exact command before it runs (you approve each step!)
4. Verifying each installation is successful
> ⚠️ **Note:** You might need to enter your computer's password for some installations. This is normal!
### 💡 Why These Tools Are Important
- **Node.js & npm:**
- Build websites with frameworks like React or Next.js
- Run JavaScript code
- Install JavaScript packages
- **Git:**
- Save different versions of your code
- Collaborate with other developers
- Back up your work
- **Package Managers:**
- Quickly install and update development tools
- Keep your environment organized and up to date
### 🧩 Notes
> 💡 **Tip:** The installation process is interactive — Cline will guide you step by step!
- All commands are shown to you for approval before they run.
- If you run into any issues, Cline will help troubleshoot them.
- You may need to enter your computer's password for certain steps.
### 🧑‍💻 Additional Tips for New Coders
#### Understanding the Terminal
The Terminal is an application where you can type commands to interact with your computer.
- **macOS:** Open it by searching for "Terminal" in Spotlight.
- **Example:**
```
$ open -a Terminal
```
#### Understanding VS Code Features
- **Terminal in VS Code:** Run commands directly from within VS Code!
- Go to **View > Terminal** or press \`Ctrl + \`\`.
- Example:
```
$ node -v
v16.14.0
```
- **Document View:** Where you edit your code files.
- Open files from the Explorer panel on the left.
- **Problems Section:** View errors or warnings in your code.
- Access it by clicking the lightbulb icon or **View > Problems**.
#### Common Features
- **Command Line Interface (CLI):** A powerful tool for running commands.
- **Permissions:** You might need to grant permissions to certain commands — this keeps your system secure.
@@ -0,0 +1,126 @@
---
title: "Model Selection Guide"
description: "Last updated: Feb 5, 2025."
---
## Understanding Context Windows
Think of a context window as your AI assistant's working memory - similar to RAM in a computer. It determines how much information the model can "remember" and process at once during your conversation. This includes:
- Your code files and conversations
- The assistant's responses
- Any documentation or additional context provided
Context windows are measured in tokens (roughly 3/4 of a word in English). Different models have different context window sizes:
- Claude 3.5 Sonnet: 200K tokens
- DeepSeek Models: 128K tokens
- Gemini Flash 2.0: 1M tokens
- Gemini 1.5 Pro: 2M tokens
When you reach the limit of your context window, older information needs to be removed to make room for new information - just like clearing RAM to run new programs. This is why sometimes AI assistants might seem to "forget" earlier parts of your conversation.
Cline helps you manage this limitation with its Context Window Progress Bar, which shows:
- Input tokens (what you've sent to the model)
- Output tokens (what the model has generated)
- A visual representation of how much of your context window you've used
- The total capacity for your chosen model
<Frame caption="Visual representation of the context window usage in Cline">
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(11).png"
alt="Context window progress bar example"
/>
</Frame>
This visibility helps you work more effectively with Cline by letting you know when you might need to start fresh or break tasks into smaller chunks.
### Model Comparison
## LLM Model Comparison for Cline (Feb 2025)
| Model | Input Cost\* | Output Cost\* | Context Window | Best For |
| ----------------- | ------------ | ------------- | -------------- | ----------------------------------- |
| Claude 3.5 Sonnet | $3.00 | $15.00 | 200K | Best code implementation & tool use |
| DeepSeek R1 | $0.55 | $2.19 | 128K | Planning & reasoning champion |
| DeepSeek V3 | $0.14 | $0.28 | 128K | Value code implementation |
| o3-mini | $1.10 | $4.40 | 200K | Flexible use, strong planning |
| Gemini Flash 2.0 | $0.00 | $0.00 | 1M | Strong all-rounder |
| Gemini 1.5 Pro | $0.00 | $0.00 | 2M | Large context processing |
\*Costs per million tokens
### Top Picks for 2025
1. **Claude 3.5 Sonnet**
- Best overall code implementation
- Most reliable tool usage
- Expensive but worth it for critical code
2. **DeepSeek R1**
- Exceptional planning & reasoning
- Great value pricing
3. **o3-mini**
- Strong for planning with adjustable reasoning
- Three reasoning modes for different needs
- Requires OpenAI Tier 3 API access
- 200K context window
4. **DeepSeek V3**
- Reliable code implementation
- Great for daily coding
- Cost-effective for implementation
5. **Gemini Flash 2.0**
- Massive 1M context window
- Improved speed and performance
- Good all-around capabilities
### Best Models by Mode (Plan or Act)
#### Planning
1. **DeepSeek R1**
- Best reasoning capabilities in class
- Excellent at breaking down complex tasks
- Strong math/algorithm planning
- MoE architecture helps with reasoning
2. **o3-mini (high reasoning)**
- Three reasoning levels:
- High: Complex planning
- Medium: Daily tasks
- Low: Quick ideas
- 200K context helps with large projects
3. **Gemini Flash 2.0**
- Massive context window for complex planning
- Strong reasoning capabilities
- Good with multi-step tasks
#### Acting (coding)
1. **Claude 3.5 Sonnet**
- Best code quality
- Most reliable with Cline tools
- Worth the premium for critical code
2. **DeepSeek V3**
- Nearly Sonnet-level code quality
- Better API stability than R1
- Great for daily coding
- Strong tool usage
3. **Gemini 1.5 Pro**
- 2M context window
- Good with complex codebases
- Reliable API
- Strong multi-file understanding
### A Note on Local Models
While running models locally might seem appealing for cost savings, we currently don't recommend any local models for use with Cline. [Local models are significantly less reliable](https://docs.cline.bot/running-models-locally/read-me-first) at using Cline's essential tools and typically retain only 1-26% of the original model's capabilities. The full cloud version of DeepSeek-R1, for example, is 671B parameters - local versions are drastically simplified copies that struggle with complex tasks and tool usage. Even with high-end hardware (RTX 3070+, 32GB+ RAM), you'll experience slower responses, less reliable tool execution, and reduced capabilities. For the best development experience, we recommend sticking with the cloud models listed above.
### Key Takeaways
1. **Plan vs Act Matters**: Choose models based on task type
2. **Real Performance > Benchmarks**: Focus on actual Cline performance
3. **Mix & Match**: Use different models for planning and implementation
4. **Cost vs Quality**: Premium models worth it for critical code
5. **Keep Backups**: Have alternatives ready for API issues
_\*Note: Based on real usage patterns and community feedback rather than just benchmarks. Your experience may vary. This is not an exhaustive list of all the models available for use within Cline._
@@ -0,0 +1,238 @@
---
title: "Our Favorite Tech Stack"
description: "A curated list of our recommended technologies and tools for building modern web applications with Cline."
---
## Recommended Stack for New Cline Users (2025)
### Your Complete Development Environment
#### Development Tools
- **VS Code** - Your code editor, [download here](https://code.visualstudio.com/)
- **GitHub** - Where your code lives, [sign up here](https://github.com)
#### Frontend
- **Next.js 14+** - React framework with App Router
- **Tailwind CSS** - Beautiful styling without writing CSS
- **TypeScript** - JavaScript, but safer and smarter
#### Backend
- **Supabase** - Your complete backend solution, [sign up with GitHub](https://supabase.com)
- PostgreSQL database
- Authentication
- File storage
- Real-time updates
#### Deployment
- **Vercel** - Where your app runs, [sign up with GitHub](https://vercel.com)
- Automatic deployments from GitHub
- Preview deployments for testing
- Production-ready CDN
#### AI Development
Choose your AI assistant based on your needs:
| Model | Input Cost (per 1M tokens) | Output Cost (per 1M tokens) | Best For |
| ----------------- | -------------------------- | --------------------------- | ------------------------------ |
| Claude 3.5 Sonnet | $3.00 | $15.00 | Production apps, complex tasks |
| DeepSeek R1 | $1.00 | $3.00 | Budget-conscious production |
| DeepSeek V3 | $0.14 | $2.20 | Budget-conscious development |
#### Free Tier Benefits
**Vercel (Hobby)**
- 100 GB data transfer/month
- 100k serverless function invocations
- 100 MB deployment size
- Automatic HTTPS & CI/CD
**Supabase (Free)**
- 500 MB database storage
- 1 GB file storage
- 50k monthly active users
- 2M real-time messages/month
**GitHub (Free)**
- Unlimited public repositories
- GitHub Actions CI/CD
- Project management tools
- Collaboration features
### Getting Started
1. Install the development essentials:
- Follow our [Development Essentials Installation Guide](https://docs.cline.bot/getting-started/getting-started-new-coders/installing-dev-essentials)
2. Set up Cline's Memory Bank:
- Follow the [Memory Bank setup instructions](https://docs.cline.bot/improving-your-prompting-skills/custom-instructions-library/cline-memory-bank)
- Create an empty `cline_docs` folder in your project root
- Create `projectBrief.md` in the `cline_docs` folder (see example below)
- Tell Cline to "initialize memory bank"
3. Add our recommended stack configuration:
- Create `.clinerules` file (see template below)
- Let Cline handle the rest!
#### Example Project Brief
```markdown
# Project Brief
## Overview
Building a [type of application] that will [main purpose].
## Core Features
- Feature 1
- Feature 2
- Feature 3
## Target Users
[Describe who will use your application]
## Technical Preferences (optional)
- Any specific technologies you want to use
- Any specific requirements or constraints
```
### .clinerules Template
```markdown
# Project Configuration
## Tech Stack
- Next.js 14+ with App Router
- Tailwind CSS for styling
- Supabase for backend
- Vercel for deployment
- GitHub for version control
## Project Structure
/src
/app # Next.js App Router pages
/components # React components
/lib # Utility functions
/types # TypeScript types
/supabase
/migrations # SQL migration files
/seed # Seed data files
/public # Static assets
## Database Migrations
SQL files in /supabase/migrations should:
- Use sequential numbering: 001, 002, etc.
- Include descriptive names
- Be reviewed by Cline before execution
Example: 001_create_users_table.sql
## Development Workflow
- Cline helps write and review code changes
- Vercel automatically deploys from main branch
- Database migrations reviewed by Cline before execution
## Security
DO NOT read or modify:
- .env files
- \*_/config/secrets._
- Any file containing API keys or credentials
```
### Learning Resources (2025)
Want to learn more about the technologies we're using? Here are some great resources:
#### Next.js and React
- [Official Learn Next.js Course](https://nextjs.org/learn) - Interactive tutorial
- [NextJS App Router: Modern Web Dev in 1 Hour](https://www.youtube.com/nextjs-modern) - Quick overview
- [Building Real-World Apps with Next.js](https://www.youtube.com/nextjs-real-world) - Practical examples
#### Supabase
- [Supabase From Scratch](https://www.udemy.com/supabase-scratch) - Comprehensive course
- [Official Quickstart Guides](https://supabase.com/docs/guides/getting-started)
- [Real-Time Apps with Next.js and Supabase](https://www.newline.co/courses/supabase-nextjs)
#### Tailwind CSS
- [Tailwind CSS Tutorial for Beginners](https://www.youtube.com/tailwind-2025)
- [Official Tailwind Documentation](https://tailwindcss.com/docs)
- Interactive course at [Scrimba Tailwind CSS Course](https://scrimba.com/learn/tailwind)
### Other Things to Know
#### Working with Git & GitHub
Git helps you track changes in your code and collaborate with others. Here are the essential commands you'll use:
**Daily Development**
```bash
# Save your changes (do this often!)
git add . # Stage all changed files
git commit -m "Add login page" # Save changes with a clear message
# Share your changes
git push origin main # Upload to GitHub
```
**Common Workflow**
1. **Start of day**: Get latest changes
```bash
bashCopygit pull origin main # Download latest code
```
2. **During development**: Save work regularly
```bash
bashCopygit add .
git commit -m "Clear message about changes"
```
3. **End of day**: Share your progress
```bash
bashCopygit push origin main # Upload to GitHub
```
**Best Practices**
- Commit often with clear messages
- Pull before starting new work
- Push completed work to share with others
- Use `.gitignore` to avoid committing sensitive files
> **Tip**: Vercel automatically deploys when you push to main!
#### Environment Variables
- Store secrets in `.env.local` for development
- Add them to Vercel project settings for production
- Never commit `.env` files to Git
#### Getting Help
1. Use `/help` in Cline chat for immediate assistance
2. Check [Cline Documentation](https://docs.cline.bot)
3. Join our [Discord Community](https://discord.gg/cline)
4. Search GitHub issues for common problems
Remember: Cline is here to help at every step. Just ask for guidance or clarification when needed!
+67
View File
@@ -0,0 +1,67 @@
---
title: "Task Management in Cline"
description: "Learn how to effectively manage your task history, use favorites, and organize your work in Cline."
---
# Task Management
As you use Cline, you'll accumulate many tasks over time. The task management system helps you organize, filter, search, and clean up your task history to keep your workspace efficient.
## Accessing Task History
You can access your task history by:
1. Clicking on the "History" button in the Cline sidebar
2. Using the command palette to search for "Cline: Show Task History"
## Task History Features
The task history view provides several powerful features:
### Searching and Filtering
- **Search Bar**: Use the fuzzy search at the top to quickly find tasks by content
- **Sort Options**: Sort tasks by:
- Newest (default)
- Oldest
- Most Expensive (highest API cost)
- Most Tokens (highest token usage)
- Most Relevant (when searching)
- **Favorites Filter**: Toggle to show only favorited tasks
### Task Actions
Each task in the history view has several actions available:
- **Open**: Click on a task to reopen it in the Cline chat
- **Favorite**: Click the star icon to mark a task as a favorite
- **Delete**: Remove individual tasks (favorites are protected from deletion)
- **Export**: Export a task's conversation to markdown
## ⭐ Task Favorites
The favorites feature allows you to mark important tasks that you want to preserve and find quickly.
### How Favorites Work
- **Marking Favorites**: Click the star icon next to any task to toggle its favorite status
- **Protection**: Favorited tasks are protected from individual and bulk deletion operations (can be overridden)
- **Filtering**: Use the favorites filter to quickly access your important tasks
## Batch Operations
The task history view supports several batch operations:
- **Select Multiple**: Use the checkboxes to select multiple tasks
- **Select All/None**: Quickly select or deselect all tasks
- **Delete Selected**: Remove all selected tasks
- **Delete All**: Remove all tasks from history (favorites are preserved unless you choose to include them)
## Best Practices
1. **Favorite Important Tasks**: Mark reference tasks or frequently accessed conversations as favorites
2. **Regular Cleanup**: Periodically remove old or unused tasks to improve performance
3. **Use Search**: Leverage the fuzzy search to quickly find specific conversations
4. **Export Valuable Tasks**: Export important tasks to markdown for external reference
Task management helps you maintain an organized workflow when using Cline, allowing you to quickly find past conversations, preserve important work, and keep your history clean and efficient.
@@ -0,0 +1,159 @@
---
title: "Context Management"
description: "Context is key to getting the most out of Cline"
---
> 💡 **Quick Reference**
>
> - Context = The information Cline knows about your project
> - Context Window = How much information Cline can hold at once
> - Use context files to maintain project knowledge
> - Reset when the context window gets full
## Understanding Context & Context Windows
<Frame caption="In a world of infinite context, the context window is what Cline currently has available">
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(2).png"
alt="In a world of infinite context, the context window is what Cline currently has available"
/>
</Frame>
Think of working with Cline like collaborating with a thorough, proactive teammate:
### How Context is Built
Cline actively builds context in two ways:
1. **Automatic Context Gathering (i.e. Cline-driven)**
- Proactively reads related files
- Explores project structure
- Analyzes patterns and relationships
- Maps dependencies and imports
- Asks clarifying questions
2. **User-Guided Context**
- Share specific files
- Provide documentation
- Answer Cline's questions
- Guide focus areas
- Share design thoughts and requirements
💡 **Key Point**: Cline isn't passive - it actively seeks to understand your project. You can either let it explore or guide its focus, especially in [Plan](https://docs.cline.bot/exploring-clines-tools/plan-and-act-modes-a-guide-to-effective-ai-development) mode.
### Context & Context Windows
Think of context like a whiteboard you and Cline share:
- **Context** is all the information available:
- What Cline has discovered
- What you've shared
- Your conversation history
- Project requirements
- Previous decisions
- **Context Window** is the size of the whiteboard itself:
- Measured in tokens (1 token ≈ 3/4 of an English word)
- Each model has a fixed size:
- Claude 3.5 Sonnet: 200,000 tokens
- DeepSeek: 64,000 tokens
- When the whiteboard is full, you need to erase (clear context) to write more
- [How Cline manages context under the hood](https://cline.bot/blog/understanding-the-new-context-window-progress-bar-in-cline)
⚠️ **Important**: Having a large context window (like Claude's 200k tokens) doesn't mean you should fill it completely. Just like a cluttered whiteboard, too much information can make it harder to focus on what's important.
## Understanding the Context Window Progress Bar
Cline provides a visual way to monitor your context window usage through a progress bar:
<Frame caption="Visual representation of the context window usage">
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(1)%20(1).png"
alt="Context window progress bar"
/>
</Frame>
### Reading the Bar
- ↑ shows input tokens (what you've sent to the LLM)
- ↓ shows output tokens (what the LLM has generated)
- The progress bar visualizes how much of your context window you've used
- The total shows your model's maximum capacity (e.g., 200k for Claude 3.5-Sonnet)
### When to Watch the Bar
- During long coding sessions
- When working with multiple files
- Before starting complex tasks
- When Cline seems to lose context
💡 **Tip**: Consider starting a fresh session when usage reaches 70-80% to maintain optimal performance.
## Working with Context Files
Context files help maintain understanding across sessions. They serve as documentation specifically designed to help AI assistants understand your project.
#### Approaches to Context Files
1. **Evergreen Project Context (i.e.** [**Memory Bank**](https://docs.cline.bot/improving-your-prompting-skills/custom-instructions-library/cline-memory-bank)**)**
- Living documentation that evolves with your project
- Updated as architecture and patterns emerge
- Example: The Memory Bank pattern maintains files like `techContext.md` and `systemPatterns.md`
- Useful for long-running projects and teams
2. **Task-Specific Context (i.e.** [**Structured Approach**](https://cline.bot/blog/building-advanced-software-with-cline-a-structured-approach)**)**
- Created for specific implementation tasks
- Document requirements, constraints, and decisions
- Example:
```markdown
# auth-system-implementation.md
## Requirements
- OAuth2 implementation
- Support for Google and GitHub
- Rate limiting on auth endpoints
## Technical Decisions
- Using Passport.js for provider integration
- JWT for session management
- Redis for rate limiting
```
3. **Knowledge Transfer Docs**
- Switch to plan mode and ask Cline to document everything you've accomplished so far, along with the remaining steps, in a markdown file.
- Copy the contents of the markdown file.
- Start a new task using that content as context.
#### Using Context Files Effectively
1. **Structure and Format**
- Use clear, consistent organization
- Include relevant examples
- Link related concepts
- Keep information focused
2. **Maintenance**
- Update after significant changes
- Version control your context files
- Remove outdated information
- Document key decisions
## Practical Tips
1. **Starting New Projects**
- Let Cline explore the codebase
- Answer its questions about structure and patterns
- Consider setting up basic context files
- Document key design decisions
2. **Ongoing Development**
- Update context files with significant changes
- Share relevant documentation
- Use Plan mode for complex discussions
- Start fresh sessions when needed
3. **Team Projects**
- Share common context files (consider using [.clinerules](https://docs.cline.bot/improving-your-prompting-skills/prompting) files in project roots)
- Document architectural decisions
- Maintain consistent patterns
- Keep documentation current
Remember: The goal is to help Cline maintain consistent understanding of your project across sessions.
+8
View File
@@ -0,0 +1,8 @@
---
title: "What is Cline?"
description: "An introduction to Cline, your AI-powered development assistant in VS Code."
---
Cline is an AI development assistant which integrates with Microsoft Visual Studio Code. It provides an interface between your IDE and LLMs facilitating code development, increasing productivity and lowering the barrier to entry for new coders. Depending on permissions, Cline can read/write files, execute commands, use your web browser, and expand its capabilities with Model Context Protocol servers.
What makes Cline distinctive is its thoughtful approach to code generation and its extensive integration capabilities. Rather than simply generating code snippets, Cline collaborates with developers by planning solutions step-by-step, maintaining awareness of the entire development environment, and requiring explicit approval for all changes. It can understand large codebases, accelerate onboarding for new engineers, and connect with hundreds of tools through its Model Context Protocol Marketplace, enabling everything from streamlined project deployments to automated incident response—all through natural language commands.
@@ -0,0 +1,69 @@
---
title: "Adding MCP Servers from GitHub"
---
This guide provides a step-by-step walkthrough of how to use Cline to build an existing MCP server from a GitHub repository.
## **Finding an MCP Server**
There are multiple places online to find MCP servers:
- **Cline can automatically add MCP servers to its list, which you can then edit.** Cline can clone repositories directly from GitHub and build the servers for you.
- **GitHub:** Two of the most common places to find MCP servers on GitHub include:
- [Official MCP servers repository](https://github.com/modelcontextprotocol/servers)
- [Awesome-MCP servers repository](https://github.com/punkpeye/awesome-mcp-servers)
- **Online directories:** Several websites list MCP servers including:
- [mcpservers.org](https://mcpservers.org/)
- [mcp.so](https://mcp.so/)
- [glama.ai/mcp/servers](https://glama.ai/mcp/servers)
These directories allow users to sort the servers by various criteria such as downloads, date, stars, and use case. Each entry provides information such as features, tools, and configuration instructions.
- **PulseMCP:** This website has a blog post discussing how AI could use MCP servers to make websites obsolete. PulseMCP also includes an FAQ section about MCP servers: [https://www.pulsemcp.com/](https://www.pulsemcp.com/)
## **Building with Cline**
1. **Initiate the Process:** Provide Cline with the following information:
- **GitHub Repository URL:** The URL of the server's repository.
- **README.md Contents:** This is optional but helpful for Cline to understand the server's purpose and configuration. You can copy the README.md file from the GitHub repository.
2. **Example Interaction with Cline:**
```
User: "Cline, I want to add the MCP server for Brave browser control. Here's the GitHub link: @https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search Can you add it?"
Cline: "OK. Cloning the repository to the MCP directory. It needs to be built because it has a 'package.json' file. Should I run 'npm run build'?"
User: "Yes, build it."
Cline: "Build complete. This server needs a browser path. Where's your Brave browser executable?"
User: "It's in '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser'."
Cline: "OK. I've updated the server config with that path and added it to 'cline_mcp_settings.json'. Anything else?"
User: "No, that's all. Let's test it."
Cline: "Great! Starting the MCP Inspector to test the server connection. After that, we can try controlling the browser from Cline."
```
3. **Cline's Actions:** Based on your instructions, Cline will perform the following:
- **Repository Cloning:** Cline will clone the repository to your local machine, usually in the directory specified in your configuration.
- **Tweaking:** You can guide Cline to modify the server's configuration. For instance:
- **User:** "This server requires an API key. Can you find where it should be added?"
- Cline may automatically update the `cline_mcp_settings.json` file or other relevant files based on your instructions.
- **Building the Server:** Cline will run the appropriate build command for the server, which is commonly `npm run build`.
- **Adding Server to Settings:** Cline will add the server's configuration to the `cline_mcp_settings.json` file.
## **Testing and Troubleshooting**
1. **Test the Server:** Once Cline finishes the build process, test the server to make sure it works as expected. Cline can assist you if you encounter any problems.
2. **MCP Inspector:** You can use the MCP Inspector to test the server's connection and functionality.
## **Best Practices**
- **Understand the Basics:** While Cline simplifies the process, it's beneficial to have a basic understanding of the server's code, the MCP protocol ([learn more](/mcp/mcp-overview)), and how to configure the server. This allows for more effective troubleshooting and customization.
- **Clear Instructions:** Provide clear and specific instructions to Cline throughout the process.
- **Testing:** Thoroughly test the server after installation and configuration to ensure it functions correctly.
- **Version Control:** Use a version control system (like Git) to track changes to the server's code.
- **Stay Updated:** Keep your MCP servers updated to benefit from the latest features and security patches.
+166
View File
@@ -0,0 +1,166 @@
---
title: "Configuring MCP Servers"
---
## Global MCP Server Inclusion Mode
Utilizing MCP servers will increase your token usage. Cline offers the ability to restrict or disable MCP server functionality as desired.
1. Click the "MCP Servers" icon in the top navigation bar of the Cline extension.
2. Select the "Installed" tab, and then Click the "Advanced MCP Settings" link at the bottom of that pane.
3. Cline will open a new settings window. find `Cline>Mcp:Mode` and make your selection from the dropdown menu.
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/MCP-settings-edit%20(1).png"
alt="MCP settings edit"
/>
</Frame>
## Managing Individual MCP Servers
Each MCP server has its own configuration panel where you can modify settings, manage tools, and control its operation. To access these settings:
1. Click the "MCP Servers" icon in the top navigation bar of the Cline extension.
2. Locate the MCP server you want to manage in the list, and open it by clicking on its name.
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/MCP-settings-individual.png"
alt="MCP settings individual"
/>
</Frame>
### Deleting a Server
1. Click the Trash icon next to the MCP server you would like to delete, or the red Delete Server button at the bottom of the MCP server config box.
**NOTE:** There is no delete confirmation dialog box
### Restarting a Server
1. Click the Restart button next to the MCP server you would like to restart, or the gray Restart Server button at the bottom of the MCP server config box.
### Enabling or Disabling a Server
1. Click the toggle switch next to the MCP server to enable/disable servers individually.
### Network Timeout
To set the maximum time to wait for a response after a tool call to the MCP server:
1. Click the `Network Timeout` dropdown at the bottom of the individual MCP server's config box and change the time. Default is 1 minute but it can be set between 30 seconds and 1 hour.
## Editing MCP Settings Files
Settings for all installed MCP servers are located in the `cline_mcp_settings.json` file:
1. Click the MCP Servers icon at the top navigation bar of the Cline pane.
2. Select the "Installed" tab.
3. Click the "Configure MCP Servers" button at the bottom of the pane.
The file uses a JSON format with a `mcpServers` object containing named server configurations:
```json
{
"mcpServers": {
"server1": {
"command": "python",
"args": ["/path/to/server.py"],
"env": {
"API_KEY": "your_api_key"
},
"alwaysAllow": ["tool1", "tool2"],
"disabled": false
}
}
}
```
_Example of MCP Server config in Cline (STDIO Transport)_
---
## Understanding Transport Types
MCP supports two transport types for server communication:
### STDIO Transport
Used for local servers running on your machine:
- Communicates via standard input/output streams
- Lower latency (no network overhead)
- Better security (no network exposure)
- Simpler setup (no HTTP server needed)
- Runs as a child process on your machine
For more in-depth information about how STDIO transport works, see [MCP Transport Mechanisms](/mcp/mcp-transport-mechanisms).
STDIO configuration example:
```json
{
"mcpServers": {
"local-server": {
"command": "node",
"args": ["/path/to/server.js"],
"env": {
"API_KEY": "your_api_key"
},
"alwaysAllow": ["tool1", "tool2"],
"disabled": false
}
}
}
```
### SSE Transport
Used for remote servers accessed over HTTP/HTTPS:
- Communicates via Server-Sent Events protocol
- Can be hosted on a different machine
- Supports multiple client connections
- Requires network access
- Allows centralized deployment and management
For more in-depth information about how SSE transport works, see [MCP Transport Mechanisms](/mcp/mcp-transport-mechanisms).
SSE configuration example:
```json
{
"mcpServers": {
"remote-server": {
"url": "https://your-server-url.com/mcp",
"headers": {
"Authorization": "Bearer your-token"
},
"alwaysAllow": ["tool3"],
"disabled": false
}
}
}
```
---
## Using MCP Tools in Your Workflow
After configuring an MCP server, Cline will automatically detect available tools and resources. To use them:
1. Type your request in Cline's conversation window
2. Cline will identify when an MCP tool can help with your task
3. Approve the tool use when prompted (or use auto-approval)
Example: "Analyze the performance of my API" might use an MCP tool that tests API endpoints.
## Troubleshooting MCP Servers
Common issues and solutions:
- **Server Not Responding:** Check if the server process is running and verify network connectivity
- **Permission Errors:** Ensure proper API keys and credentials are configured in your `mcp_settings.json` file
- **Tool Not Available:** Confirm the server is properly implementing the tool and it's not disabled in settings
- **Slow Performance:** Try adjusting the network timeout value for the specific MCP server
+132
View File
@@ -0,0 +1,132 @@
---
title: "Connecting to a Remote Server"
description: "The Model Context Protocol (MCP) allows Cline to communicate with external servers that provide additional tools and resources to extend its capabilities. This guide explains how to add and connect to remote MCP servers through the MCP Servers interface."
---
## Adding and Managing Remote MCP Servers
### Accessing the MCP Servers Interface
To access the MCP Servers interface in Cline:
1. Click on the Cline icon in the VSCode sidebar
2. Open the menu (⋮) in the top right corner of the Cline panel
3. Select "MCP Servers" from the dropdown menu
### Understanding the MCP Servers Interface
The MCP Servers interface is divided into three main tabs:
- **Marketplace**: Discover and install pre-configured MCP servers (if enabled)
- **Remote Servers**: Connect to existing MCP servers via URL endpoints
- **Installed**: Manage your connected MCP servers
### Adding a Remote MCP Server
The "Remote Servers" tab allows you to connect to any MCP server that's accessible via a URL endpoint:
1. Click on the "Remote Servers" tab in the MCP Servers interface
2. Fill in the required information:
- **Server Name**: Provide a unique, descriptive name for the server
- **Server URL**: Enter the complete URL endpoint of the MCP server (e.g., `https://example.com/mcp-sse`)
3. Click "Add Server" to initiate the connection
4. Cline will attempt to connect to the server and display the connection status
> **Note**: When connecting to a remote server, ensure you trust the source, as MCP servers can execute code in your environment.
### Remote Server Discovery
If you're looking for MCP servers to connect to, several third-party marketplaces provide directories of available servers with various capabilities.
> **Warning**: The following third-party marketplaces are listed for informational purposes only. Cline does not endorse, verify, or take responsibility for any servers listed on these marketplaces. These servers are cloud-hosted services that process your requests and may have access to data you share with them. Always review privacy policies and terms of use before connecting to third-party services.
#### Composio MCP Integration
[Composio's MCP Marketplace](https://mcp.composio.dev/) provides access to a wide range of third-party servers that support the Model Context Protocol (MCP). These servers expose APIs for services like GitHub, Notion, Slack, and others. Each server includes configuration instructions and built-in authentication support (e.g. OAuth or API keys). To connect, locate the desired service in the marketplace and follow the integration steps provided there.
#### Connecting via Smithery
Smithery is a third-party MCP server marketplace that allows users to discover and connect to a variety of Model Context Protocol (MCP) servers. If you're using an MCP-compatible client (such as Cursor, Claude Desktop, or Cline), you can browse available servers and integrate them directly into your workflow.
To explore available options, visit the Smithery marketplace: [https://smithery.ai](https://smithery.ai)
Please note: Smithery is maintained independently and is not affiliated with our project. Use at your own discretion.
### Managing Installed MCP Servers
Once added, your MCP servers appear in the "Installed" tab where you can:
#### View Server Status
Each server displays its current status:
- **Green dot**: Connected and ready to use
- **Yellow dot**: In the process of connecting
- **Red dot**: Disconnected or experiencing errors
#### Configure Server Settings
Click on a server to expand its settings panel:
1. **Tools & Resources**:
- View all available tools and resources from the server
- Configure auto-approval settings for tools (if enabled)
2. **Request Timeout**:
- Set how long Cline should wait for server responses
- Options range from 30 seconds to 1 hour
3. **Server Management**:
- **Restart Server**: Reconnect if the server becomes unresponsive
- **Delete Server**: Remove the server from your configuration
#### Enable/Disable Servers
Toggle the switch next to each server to enable or disable it:
- **Enabled**: Cline can use the server's tools and resources
- **Disabled**: The server remains in your configuration but is not active
### Troubleshooting Connection Issues
If a server fails to connect:
1. An error message will be displayed with details about the failure
2. Check that the server URL is correct and the server is running
3. Use the "Restart Server" button to attempt reconnection
4. If problems persist, you can delete the server and try adding it again
### Advanced Configuration
For advanced users, Cline stores MCP server configurations in a JSON file that can be modified:
1. In the "Installed" tab, click "Configure MCP Servers" to access the settings file
2. The configuration for each server follows this format:
```json
{
"mcpServers": {
"exampleServer": {
"url": "https://example.com/mcp-sse",
"disabled": false,
"autoApprove": ["tool1", "tool2"],
"timeout": 30
}
}
}
```
Key configuration options:
- **url**: The endpoint URL (for remote servers)
- **disabled**: Whether the server is currently enabled (true/false)
- **autoApprove**: List of tool names that don't require confirmation
- **timeout**: Maximum time in seconds to wait for server responses
For additional MCP settings, click the "Advanced MCP Settings" link to access VSCode settings.
### Using MCP Server Tools
Once connected, Cline can use the tools and resources provided by the MCP server. When Cline suggests using an MCP tool:
1. A tool approval prompt will appear (unless auto-approved)
2. Review the tool details and parameters before approving
3. The tool will execute and return results to Cline
+199
View File
@@ -0,0 +1,199 @@
---
title: "MCP Made Easy"
description: "Learn how to use the MCP Marketplace to discover, install, and configure MCP servers that enhance Cline's capabilities with additional tools and resources."
---
## What's an MCP Server?
MCP servers are specialized extensions that enhance Cline's capabilities. They enable Cline to perform additional tasks like fetching web pages, processing images, accessing APIs, and much more.
## MCP Marketplace Walkthrough
The MCP Marketplace provides a one-click installation experience for hundreds of MCP servers across various categories.
### 1. Access the Marketplace
- In Cline, click the "Extensions" button (square icon) in the top toolbar
- The MCP marketplace will open, showing available servers by category
### 2. Browse and Select a Server
- Browse servers by category (Search, File-systems, Browser-automation, Research-data, etc.)
- Click on a server to see details about its capabilities and requirements
### 3. Install and Configure
- Click the install button for your chosen server
- If the server requires an API key (most do), Cline will guide you through:
- Where to get the API key
- How to enter it securely
- The server will be added to your MCP settings automatically
### 4. Verify Installation
- Cline will show confirmation when installation is complete
- Check the server status in Cline's MCP settings UI
### 5. Using Your New Server
- After successful installation, Cline will automatically integrate the server's capabilities
- You'll see new tools and resources available in Cline's system prompt
- Simply ask Cline to use the capabilities of your new server
- Example: "Search the web for recent React updates using Perplexity"
**Corporate Users:** If you're using Cline in a corporate environment, ensure you have permission to install third-party MCP servers according to your organization's security policies.
## What Happens Behind the Scenes
When you install an MCP server, several things happen automatically:
### 1. Installation Process
- The server code is cloned/installed to `/Users/<username>/Documents/Cline/MCP/`
- Dependencies are installed
- The server is built (TypeScript/JavaScript compilation or Python package installation)
### 2. Configuration
- The MCP settings file is updated with your server configuration
- This file is located at: `/Users/<username>/Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json`
- Environment variables (like API keys) are securely stored
- The server path is registered
### 3. Server Launch
- Cline detects the configuration change
- Cline launches your server as a separate process
- Communication is established via stdio or HTTP
### 4. Integration with Cline
- Your server's capabilities are added to Cline's system prompt
- Tools become available via `use_mcp_tool` commands
- Resources become available via `access_mcp_resource` commands
- Cline can now use these capabilities when prompted by the user
## Troubleshooting
### System Requirements
Make sure your system meets these requirements:
- **Node.js 18.x or newer**
- Check by running: `node --version`
- Install from: https://nodejs.org/
- Required for JavaScript/TypeScript implementations
- **Python 3.10 or newer**
- Check by running: `python --version`
- Install from: https://python.org/
- Note: Some specialized implementations may require Python 3.11+
- **UV Package Manager**
- Modern Python package manager for dependency isolation
- Install using:
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```
Or: `pip install uv`
- Verify with: `uv --version`
If any of these commands fail or show older versions, please install/update before continuing!
### Common Installation Issues
- Ensure your internet connection is stable
- Check that you have the necessary permissions to install new software
- Verify that the API key was entered correctly (if required)
- Check the server status in the MCP settings UI for any error messages
### How to Remove an MCP Server
To completely remove a faulty MCP server:
1. Open the MCP settings file: `/Users/<username>/Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json`
2. Delete the entire entry for your server from the `mcpServers` object
3. Save the file
4. Restart Cline
### I'm Still Getting an Error
If you're getting an error when using an MCP server, you can try the following:
- Check the MCP settings file for errors
- Use a Claude Sonnet model for installation
- Verify that paths to your server's files are correct
- Ensure all required environment variables are set
- Check if another process is using the same port (for HTTP-based servers)
- Try removing and reinstalling the server (remove from both the `cline_mcp_settings.json` file and the `/Users/<username>/Documents/Cline/MCP/` directory)
- Use a terminal and run the command with its arguments directly. This will allow you to see the same errors that Cline is seeing
## MCP Server Rules
Cline is already aware of your active MCP servers and what they are for, but when you have a lot of MCP servers enabled, it can be useful to define when to use each server.
Utilize a `.clinerules` file or custom instructions to support intelligent MCP server activation through keyword-based triggers, making Cline's tool selection more intuitive and context-aware.
### How MCP Rules Work
MCP Rules group your connected MCP servers into functional categories and define trigger keywords that activate them automatically when detected in your conversations with Cline.
```json
{
"mcpRules": {
"webInteraction": {
"servers": ["firecrawl-mcp-server", "fetch-mcp"],
"triggers": ["web", "scrape", "browse", "website"],
"description": "Tools for web browsing and scraping"
}
}
}
```
### Configuration Structure
1. **Categories**: Group related servers (e.g., "webInteraction", "mediaAndDesign")
2. **Servers**: List server names in each category
3. **Triggers**: Keywords that activate these servers
4. **Description**: Human-readable category explanation
### Benefits of MCP Rules
- **Contextual Tool Selection**: Cline selects appropriate tools based on conversation context
- **Reduced Friction**: No need to manually specify which tool to use
- **Organized Capabilities**: Logically group related tools and servers
- **Prioritization**: Handle ambiguous cases with explicit priority ordering
### Example Usage
When you write "Can you scrape this website?", Cline detects "scrape" and "website" as triggers, automatically selecting web-related MCP servers.
For finance tasks like "What's Apple's stock price?", keywords like "stock" and "price" trigger finance-related servers.
### Quick Start Template
```json
{
"mcpRules": {
"category1": {
"servers": ["server-name-1", "server-name-2"],
"triggers": ["keyword1", "keyword2", "phrase1", "phrase2"],
"description": "Description of what these tools do"
},
"category2": {
"servers": ["server-name-3"],
"triggers": ["keyword3", "keyword4", "phrase3"],
"description": "Description of what these tools do"
},
"category3": {
"servers": ["server-name-4", "server-name-5"],
"triggers": ["keyword5", "keyword6", "phrase4"],
"description": "Description of what these tools do"
}
},
"defaultBehavior": {
"priorityOrder": ["category1", "category2", "category3"],
"fallbackBehavior": "Ask user which tool would be most appropriate"
}
}
```
Add this to your `.clinerules` file or to your custom instructions to make Cline's MCP server selection more intuitive and context-aware.
+107
View File
@@ -0,0 +1,107 @@
---
title: "MCP Overview"
description: "Learn about Model Context Protocol (MCP) servers, their capabilities, and how Cline can help build and use them. MCP standardizes how applications provide context to LLMs, acting like a USB-C port for AI applications."
---
## Quick Links
- [Building MCP Servers from GitHub](/mcp/adding-mcp-servers-from-github)
- [Building Custom MCP Servers from Scratch](/mcp/mcp-server-development-protocol)
## Overview
Model Context Protocol is an open protocol that standardizes how applications provide context to LLMs. Think of MCP like a USB-C port for AI applications; it provides a standardized way to connect AI models to different data sources and tools. MCP servers act as intermediaries between large language models (LLMs), such as Claude, and external tools or data sources. They are small programs that expose functionalities to LLMs, enabling them to interact with the outside world through the MCP. An MCP server is essentially like an API that an LLM can use.
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/mcp-diagram.png"
alt="MCP diagram showing how MCP servers connect LLMs to external tools and data sources"
/>
</Frame>
## Key Concepts
MCP servers define a set of "**tools,**" which are functions the LLM can execute. These tools offer a wide range of capabilities.
**Here's how MCP works:**
- **MCP hosts** discover the capabilities of connected servers and load their tools, prompts, and resources.
- **Resources** provide consistent access to read-only data, akin to file paths or database queries.
- **Security** is ensured as servers isolate credentials and sensitive data. Interactions require explicit user approval.
## Use Cases
The potential of MCP servers is vast. They can be used for a variety of purposes.
**Here are some concrete examples of how MCP servers can be used:**
- **Web Services and API Integration:**
- Monitor GitHub repositories for new issues
- Post updates to Twitter based on specific triggers
- Retrieve real-time weather data for location-based services
- **Browser Automation:**
- Automate web application testing
- Scrape e-commerce sites for price comparisons
- Generate screenshots for website monitoring
- **Database Queries:**
- Generate weekly sales reports
- Analyze customer behavior patterns
- Create real-time dashboards for business metrics
- **Project and Task Management:**
- Automate Jira ticket creation based on code commits
- Generate weekly progress reports
- Create task dependencies based on project requirements
- **Codebase Documentation:**
- Generate API documentation from code comments
- Create architecture diagrams from code structure
- Maintain up-to-date README files
## Getting Started
Cline does not come with any pre-installed MCP servers. You'll need to find and install them separately.
**Choose the right approach for your needs:**
- **Community Repositories:** Check for community-maintained lists of MCP servers on GitHub. See [Adding MCP Servers from Github](/mcp/adding-mcp-servers-from-github)
- **Cline Marketplace:** Install one from Cline's [MCP Marketplace](/mcp/mcp-marketplace)
- **Ask Cline:** You can ask Cline to help you find or create MCP servers
- **Build Your Own:** Create custom MCP servers using the [MCP SDK](https://github.com/modelcontextprotocol/)
- **Customize Existing Servers:** Modify existing servers to fit your specific requirements
## Integration with Cline
Cline simplifies the building and use of MCP servers through its AI capabilities.
### Building MCP Servers
- **Natural language understanding:** Instruct Cline in natural language to build an MCP server by describing its functionalities. Cline will interpret your instructions and generate the necessary code.
- **Cloning and building servers:** Cline can clone existing MCP server repositories from GitHub and build them automatically.
- **Configuration and dependency management:** Cline handles configuration files, environment variables, and dependencies.
- **Troubleshooting and debugging:** Cline helps identify and resolve errors during development.
### Using MCP Servers
- **Tool execution:** Cline seamlessly integrates with MCP servers, allowing you to execute their defined tools.
- **Context-aware interactions:** Cline can intelligently suggest using relevant tools based on conversation context.
- **Dynamic integrations:** Combine multiple MCP server capabilities for complex tasks. For example, Cline could use a GitHub server to get data and a Notion server to create a formatted report.
## Security Considerations
When working with MCP servers, it's important to follow security best practices:
- **Authentication:** Always use secure authentication methods for API access
- **Environment Variables:** Store sensitive information in environment variables
- **Access Control:** Limit server access to authorized users only
- **Data Validation:** Validate all inputs to prevent injection attacks
- **Logging:** Implement secure logging practices without exposing sensitive data
## Resources
There are various resources available for finding and learning about MCP servers.
**Here are some links to resources for finding and learning about MCP servers:**
- **GitHub Repositories:** [https://github.com/modelcontextprotocol/servers](https://github.com/modelcontextprotocol/servers) and [https://github.com/punkpeye/awesome-mcp-servers](https://github.com/punkpeye/awesome-mcp-servers)
- **Online Directories:** [https://mcpservers.org/](https://mcpservers.org/), [https://mcp.so/](https://mcp.so/), and [https://glama.ai/mcp/servers](https://glama.ai/mcp/servers)
- **PulseMCP:** [https://www.pulsemcp.com/](https://www.pulsemcp.com/)
- **YouTube Tutorial (AI-Driven Coder):** A video guide for building and using MCP servers: [https://www.youtube.com/watch?v=b5pqTNiuuJg](https://www.youtube.com/watch?v=b5pqTNiuuJg)
@@ -0,0 +1,705 @@
---
title: "MCP Server Development Protocol"
description: "This protocol is designed to streamline the development process of building MCP servers with Cline."
---
> 🚀 **Build and share your MCP servers with the world.** Once you've created a great MCP server, submit it to the [Cline MCP Marketplace](https://github.com/cline/mcp-marketplace) to make it discoverable and one-click installable by thousands of developers.
## What Are MCP Servers?
Model Context Protocol (MCP) servers extend AI assistants like Cline by giving them the ability to:
- Access external APIs and services
- Retrieve real-time data
- Control applications and local systems
- Perform actions beyond what text prompts alone can achieve
Without MCP, AI assistants are powerful but isolated. With MCP, they gain the ability to interact with virtually any digital system.
## The Development Protocol
The heart of effective MCP server development is following a structured protocol. This protocol is implemented through a `.clinerules` file that lives at the **root** of your MCP working directory (/Users/your-name/Documents/Cline/MCP).
### Using `.clinerules` Files
A `.clinerules` file is a special configuration that Cline reads automatically when working in the directory where it's placed. These files:
- Configure Cline's behavior and enforce best practices
- Switch Cline into a specialized MCP development mode
- Provide a step-by-step protocol for building servers
- Implement safety measures like preventing premature completion
- Guide you through planning, implementation, and testing phases
Here's the complete MCP Server Development Protocol that should be placed in your `.clinerules` file:
````markdown
# MCP Server Development Protocol
⚠️ CRITICAL: DO NOT USE attempt_completion BEFORE TESTING ⚠️
## Step 1: Planning (PLAN MODE)
- What problem does this tool solve?
- What API/service will it use?
- What are the authentication requirements?
□ Standard API key
□ OAuth (requires separate setup script)
□ Other credentials
## Step 2: Implementation (ACT MODE)
1. Bootstrap
- For web services, JavaScript integration, or Node.js environments:
```bash
npx @modelcontextprotocol/create-server my-server
cd my-server
npm install
```
- For data science, ML workflows, or Python environments:
```bash
pip install mcp
# Or with uv (recommended)
uv add "mcp[cli]"
```
2. Core Implementation
- Use MCP SDK
- Implement comprehensive logging
- TypeScript (for web/JS projects):
```typescript
console.error("[Setup] Initializing server...")
console.error("[API] Request to endpoint:", endpoint)
console.error("[Error] Failed with:", error)
```
- Python (for data science/ML projects):
```python
import logging
logging.error('[Setup] Initializing server...')
logging.error(f'[API] Request to endpoint: {endpoint}')
logging.error(f'[Error] Failed with: {str(error)}')
```
- Add type definitions
- Handle errors with context
- Implement rate limiting if needed
3. Configuration
- Get credentials from user if needed
- Add to MCP settings:
- For TypeScript projects:
```json
{
"mcpServers": {
"my-server": {
"command": "node",
"args": ["path/to/build/index.js"],
"env": {
"API_KEY": "key"
},
"disabled": false,
"autoApprove": []
}
}
}
```
- For Python projects:
```bash
# Directly with command line
mcp install server.py -v API_KEY=key
# Or in settings.json
{
"mcpServers": {
"my-server": {
"command": "python",
"args": ["server.py"],
"env": {
"API_KEY": "key"
},
"disabled": false,
"autoApprove": []
}
}
}
```
## Step 3: Testing (BLOCKER ⛔️)
<thinking>
BEFORE using attempt_completion, I MUST verify:
□ Have I tested EVERY tool?
□ Have I confirmed success from the user for each test?
□ Have I documented the test results?
If ANY answer is "no", I MUST NOT use attempt_completion.
</thinking>
1. Test Each Tool (REQUIRED)
□ Test each tool with valid inputs
□ Verify output format is correct
⚠️ DO NOT PROCEED UNTIL ALL TOOLS TESTED
## Step 4: Completion
❗ STOP AND VERIFY:
□ Every tool has been tested with valid inputs
□ Output format is correct for each tool
Only after ALL tools have been tested can attempt_completion be used.
## Key Requirements
- ✓ Must use MCP SDK
- ✓ Must have comprehensive logging
- ✓ Must test each tool individually
- ✓ Must handle errors gracefully
- ⛔️ NEVER skip testing before completion
````
When this `.clinerules` file is present in your working directory, Cline will:
1. Start in **PLAN MODE** to design your server before implementation
2. Enforce proper implementation patterns in **ACT MODE**
3. Require testing of all tools before allowing completion
4. Guide you through the entire development lifecycle
## Getting Started
Creating an MCP server requires just a few simple steps to get started:
### 1. Create a `.clinerules` file (🚨 IMPORTANT)
First, add a `.clinerules` file to the root of your MCP working directory using the protocol above. This file configures Cline to use the MCP development protocol when working in this folder.
### 2. Start a Chat with a Clear Description
Begin your Cline chat by clearly describing what you want to build. Be specific about:
- The purpose of your MCP server
- Which API or service you want to integrate with
- Any specific tools or features you need
For example:
```plaintext
I want to build an MCP server for the AlphaAdvantage financial API.
It should allow me to get real-time stock data, perform technical
analysis, and retrieve company financial information.
```
### 3. Work Through the Protocol
Cline will automatically start in PLAN MODE, guiding you through the planning process:
- Discussing the problem scope
- Reviewing API documentation
- Planning authentication methods
- Designing tool interfaces
When ready, switch to ACT MODE using the toggle at the bottom of the chat to begin implementation.
### 4. Provide API Documentation Early
One of the most effective ways to help Cline build your MCP server is to share official API documentation right at the start:
```plaintext
Here's the API documentation for the service:
[Paste API documentation here]
```
Providing comprehensive API details (endpoints, authentication, data structures) significantly improves Cline's ability to implement an effective MCP server.
## Understanding the Two Modes
### PLAN MODE
In this collaborative phase, you work with Cline to design your MCP server:
- Define the problem scope
- Choose appropriate APIs
- Plan authentication methods
- Design the tool interfaces
- Determine data formats
### ACT MODE
Once planning is complete, Cline helps implement the server:
- Set up the project structure
- Write the implementation code
- Configure settings
- Test each component thoroughly
- Finalize documentation
## Case Study: AlphaAdvantage Stock Analysis Server
Let's walk through the development process of our AlphaAdvantage MCP server, which provides stock data analysis and reporting capabilities.
### Planning Phase
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/planning-phase.gif"
alt="Planning phase demonstration"
/>
</Frame>
During the planning phase, we:
1. **Defined the problem**: Users need access to financial data, stock analysis, and market insights directly through their AI assistant
2. **Selected the API**: AlphaAdvantage API for financial market data
- Standard API key authentication
- Rate limits of 5 requests per minute (free tier)
- Various endpoints for different financial data types
3. **Designed the tools needed**:
- Stock overview information (current price, company details)
- Technical analysis with indicators (RSI, MACD, etc.)
- Fundamental analysis (financial statements, ratios)
- Earnings report data
- News and sentiment analysis
4. **Planned data formatting**:
- Clean, well-formatted markdown output
- Tables for structured data
- Visual indicators (↑/↓) for trends
- Proper formatting of financial numbers
### Implementation
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/building-mcp-plugin.gif"
alt="Building MCP plugin demonstration"
/>
</Frame>
We began by bootstrapping the project:
```bash
npx @modelcontextprotocol/create-server alphaadvantage-mcp
cd alphaadvantage-mcp
npm install axios node-cache
```
Next, we structured our project with:
```plaintext
src/
├── api/
│ └── alphaAdvantageClient.ts # API client with rate limiting & caching
├── formatters/
│ └── markdownFormatter.ts # Output formatters for clean markdown
└── index.ts # Main MCP server implementation
```
#### API Client Implementation
The API client implementation included:
- **Rate limiting**: Enforcing the 5 requests per minute limit
- **Caching**: Reducing API calls with strategic caching
- **Error handling**: Robust error detection and reporting
- **Typed interfaces**: Clear TypeScript types for all data
Key implementation details:
```typescript
/**
* Manage rate limiting based on free tier (5 calls per minute)
*/
private async enforceRateLimit() {
if (this.requestsThisMinute >= 5) {
console.error("[Rate Limit] Rate limit reached. Waiting for next minute...");
return new Promise<void>((resolve) => {
const remainingMs = 60 * 1000 - (Date.now() % (60 * 1000));
setTimeout(resolve, remainingMs + 100); // Add 100ms buffer
});
}
this.requestsThisMinute++;
return Promise.resolve();
}
```
#### Markdown Formatting
We implemented formatters to display financial data beautifully:
```typescript
/**
* Format company overview into markdown
*/
export function formatStockOverview(overviewData: any, quoteData: any): string {
// Extract data
const overview = overviewData
const quote = quoteData["Global Quote"]
// Calculate price change
const currentPrice = parseFloat(quote["05. price"] || "0")
const priceChange = parseFloat(quote["09. change"] || "0")
const changePercent = parseFloat(quote["10. change percent"]?.replace("%", "") || "0")
// Format markdown
let markdown = `# ${overview.Symbol} (${overview.Name}) - ${formatCurrency(currentPrice)} ${addTrendIndicator(priceChange)}${changePercent > 0 ? "+" : ""}${changePercent.toFixed(2)}%\n\n`
// Add more details...
return markdown
}
```
#### Tool Implementation
We defined five tools with clear interfaces:
```typescript
server.setRequestHandler(ListToolsRequestSchema, async () => {
console.error("[Setup] Listing available tools")
return {
tools: [
{
name: "get_stock_overview",
description: "Get basic company info and current quote for a stock symbol",
inputSchema: {
type: "object",
properties: {
symbol: {
type: "string",
description: "Stock symbol (e.g., 'AAPL')",
},
market: {
type: "string",
description: "Optional market (e.g., 'US')",
default: "US",
},
},
required: ["symbol"],
},
},
// Additional tools defined here...
],
}
})
```
Each tool's handler included:
- Input validation
- API client calls with error handling
- Markdown formatting of responses
- Comprehensive logging
### Testing Phase
This critical phase involved systematically testing each tool:
1. First, we configured the MCP server in the settings:
```json
{
"mcpServers": {
"alphaadvantage-mcp": {
"command": "node",
"args": ["/path/to/alphaadvantage-mcp/build/index.js"],
"env": {
"ALPHAVANTAGE_API_KEY": "YOUR_API_KEY"
},
"disabled": false,
"autoApprove": []
}
}
}
```
2. Then we tested each tool individually:
- **get_stock_overview**: Retrieved AAPL stock overview information
```markdown
# AAPL (Apple Inc) - $241.84 ↑+1.91%
**Sector:** TECHNOLOGY
**Industry:** ELECTRONIC COMPUTERS
**Market Cap:** 3.63T
**P/E Ratio:** 38.26
...
```
- **get_technical_analysis**: Obtained price action and RSI data
```markdown
# Technical Analysis: AAPL
## Daily Price Action
Current Price: $241.84 (↑$4.54, +1.91%)
### Recent Daily Prices
| Date | Open | High | Low | Close | Volume |
| ---------- | ------- | ------- | ------- | ------- | ------ |
| 2025-02-28 | $236.95 | $242.09 | $230.20 | $241.84 | 56.83M |
...
```
- **get_earnings_report**: Retrieved MSFT earnings history and formatted report
```markdown
# Earnings Report: MSFT (Microsoft Corporation)
**Sector:** TECHNOLOGY
**Industry:** SERVICES-PREPACKAGED SOFTWARE
**Current EPS:** $12.43
## Recent Quarterly Earnings
| Quarter | Date | EPS Estimate | EPS Actual | Surprise % |
| ---------- | ---------- | ------------ | ---------- | ---------- |
| 2024-12-31 | 2025-01-29 | $3.11 | $3.23 | ↑4.01% |
...
```
### Challenges and Solutions
During development, we encountered several challenges:
1. **API Rate Limiting**:
- **Challenge**: Free tier limited to 5 calls per minute
- **Solution**: Implemented queuing, enforced rate limits, and added comprehensive caching
2. **Data Formatting**:
- **Challenge**: Raw API data not user-friendly
- **Solution**: Created formatting utilities for consistent display of financial data
3. **Timeout Issues**:
- **Challenge**: Complex tools making multiple API calls could timeout
- **Solution**: Suggested breaking complex tools into smaller pieces, optimizing caching
### Lessons Learned
Our AlphaAdvantage implementation taught us several key lessons:
1. **Plan for API Limits**: Understand and design around API rate limits from the beginning
2. **Cache Strategically**: Identify high-value caching opportunities to improve performance
3. **Format for Readability**: Invest in good data formatting for improved user experience
4. **Test Every Path**: Test all tools individually before completion
5. **Handle API Complexity**: For APIs requiring multiple calls, design tools with simpler scopes
## Core Implementation Best Practices
### Comprehensive Logging
Effective logging is essential for debugging MCP servers:
```typescript
// Start-up logging
console.error("[Setup] Initializing AlphaAdvantage MCP server...")
// API request logging
console.error(`[API] Getting stock overview for ${symbol}`)
// Error handling with context
console.error(`[Error] Tool execution failed: ${error.message}`)
// Cache operations
console.error(`[Cache] Using cached data for: ${cacheKey}`)
```
### Strong Typing
Type definitions prevent errors and improve maintainability:
```typescript
export interface AlphaAdvantageConfig {
apiKey: string
cacheTTL?: Partial<typeof DEFAULT_CACHE_TTL>
baseURL?: string
}
/**
* Validate that a stock symbol is provided and looks valid
*/
function validateSymbol(symbol: unknown): asserts symbol is string {
if (typeof symbol !== "string" || symbol.trim() === "") {
throw new McpError(ErrorCode.InvalidParams, "A valid stock symbol is required")
}
// Basic symbol validation (letters, numbers, dots)
const symbolRegex = /^[A-Za-z0-9.]+$/
if (!symbolRegex.test(symbol)) {
throw new McpError(ErrorCode.InvalidParams, `Invalid stock symbol: ${symbol}`)
}
}
```
### Intelligent Caching
Reduce API calls and improve performance:
```typescript
// Default cache TTL in seconds
const DEFAULT_CACHE_TTL = {
STOCK_OVERVIEW: 60 * 60, // 1 hour
TECHNICAL_ANALYSIS: 60 * 30, // 30 minutes
FUNDAMENTAL_ANALYSIS: 60 * 60 * 24, // 24 hours
EARNINGS_REPORT: 60 * 60 * 24, // 24 hours
NEWS: 60 * 15, // 15 minutes
}
// Check cache first
const cachedData = this.cache.get<T>(cacheKey)
if (cachedData) {
console.error(`[Cache] Using cached data for: ${cacheKey}`)
return cachedData
}
// Cache successful responses
this.cache.set(cacheKey, response.data, cacheTTL)
```
### Graceful Error Handling
Implement robust error handling that maintains a good user experience:
```typescript
try {
switch (request.params.name) {
case "get_stock_overview": {
// Implementation...
}
// Other cases...
default:
throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${request.params.name}`)
}
} catch (error) {
console.error(`[Error] Tool execution failed: ${error instanceof Error ? error.message : String(error)}`)
if (error instanceof McpError) {
throw error
}
return {
content: [
{
type: "text",
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
},
],
isError: true,
}
}
```
## MCP Resources
Resources let your MCP servers expose data to Cline without executing code. They're perfect for providing context like files, API responses, or database records that Cline can reference during conversations.
### Adding Resources to Your MCP Server
1. **Define the resources** your server will expose:
```typescript
server.setRequestHandler(ListResourcesRequestSchema, async () => {
return {
resources: [
{
uri: "file:///project/readme.md",
name: "Project README",
mimeType: "text/markdown",
},
],
}
})
```
2. **Implement read handlers** to deliver the content:
```typescript
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
if (request.params.uri === "file:///project/readme.md") {
const content = await fs.promises.readFile("/path/to/readme.md", "utf-8")
return {
contents: [
{
uri: request.params.uri,
mimeType: "text/markdown",
text: content,
},
],
}
}
throw new Error("Resource not found")
})
```
Resources make your MCP servers more context-aware, allowing Cline to access specific information without requiring you to copy/paste. For more information, refer to the [official documentation](https://modelcontextprotocol.io/docs/concepts/resources).
## Common Challenges and Solutions
### API Authentication Complexities
**Challenge**: APIs often have different authentication methods.
**Solution**:
- For API keys, use environment variables in the MCP configuration
- For OAuth, create a separate script to obtain refresh tokens
- Store sensitive tokens securely
```typescript
// Authenticate using API key from environment
const API_KEY = process.env.ALPHAVANTAGE_API_KEY
if (!API_KEY) {
console.error("[Error] Missing ALPHAVANTAGE_API_KEY environment variable")
process.exit(1)
}
// Initialize API client
const apiClient = new AlphaAdvantageClient({
apiKey: API_KEY,
})
```
### Missing or Limited API Features
**Challenge**: APIs may not provide all the functionality you need.
**Solution**:
- Implement fallbacks using available endpoints
- Create simulated functionality where necessary
- Transform API data to match your needs
### API Rate Limiting
**Challenge**: Most APIs have rate limits that can cause failures.
**Solution**:
- Implement proper rate limiting
- Add intelligent caching
- Provide graceful degradation
- Add transparent errors about rate limits
```typescript
if (this.requestsThisMinute >= 5) {
console.error("[Rate Limit] Rate limit reached. Waiting for next minute...")
return new Promise<void>((resolve) => {
const remainingMs = 60 * 1000 - (Date.now() % (60 * 1000))
setTimeout(resolve, remainingMs + 100) // Add 100ms buffer
})
}
```
## Additional Resources
- [MCP Protocol Documentation](https://github.com/modelcontextprotocol/mcp)
- [MCP SDK Documentation](https://github.com/modelcontextprotocol/sdk-js)
- [MCP Server Examples](https://github.com/modelcontextprotocol/servers)
+197
View File
@@ -0,0 +1,197 @@
---
title: "MCP Transport Mechanisms"
description: "Learn about the two primary transport mechanisms for communication between Cline and MCP servers: Standard Input/Output (STDIO) and Server-Sent Events (SSE). Each has distinct characteristics, advantages, and use cases."
---
Model Context Protocol (MCP) supports two primary transport mechanisms for communication between Cline and MCP servers: Standard Input/Output (STDIO) and Server-Sent Events (SSE). Each has distinct characteristics, advantages, and use cases.
## STDIO Transport
STDIO transport runs locally on your machine and communicates via standard input/output streams.
### How STDIO Transport Works
1. The client (Cline) spawns an MCP server as a child process
2. Communication happens through process streams: client writes to server's STDIN, server responds to STDOUT
3. Each message is delimited by a newline character
4. Messages are formatted as JSON-RPC 2.0
```plaintext
Client Server
| |
|<---- JSON message ----->| (via STDIN)
| | (processes request)
|<---- JSON message ------| (via STDOUT)
| |
```
### STDIO Characteristics
- **Locality**: Runs on the same machine as Cline
- **Performance**: Very low latency and overhead (no network stack involved)
- **Simplicity**: Direct process communication without network configuration
- **Relationship**: One-to-one relationship between client and server
- **Security**: Inherently more secure as no network exposure
### When to Use STDIO
STDIO transport is ideal for:
- Local integrations and tools running on the same machine
- Security-sensitive operations
- Low-latency requirements
- Single-client scenarios (one Cline instance per server)
- Command-line tools or IDE extensions
### STDIO Implementation Example
```typescript
import { Server } from "@modelcontextprotocol/sdk/server/index.js"
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
const server = new Server({ name: "local-server", version: "1.0.0" })
// Register tools...
// Use STDIO transport
const transport = new StdioServerTransport(server)
transport.listen()
```
## SSE Transport
Server-Sent Events (SSE) transport runs on a remote server and communicates over HTTP/HTTPS.
### How SSE Transport Works
1. The client (Cline) connects to the server's SSE endpoint via HTTP GET request
2. This establishes a persistent connection where the server can push events to the client
3. For client-to-server communication, the client makes HTTP POST requests to a separate endpoint
4. Communication happens over two channels:
- Event Stream (GET): Server-to-client updates
- Message Endpoint (POST): Client-to-server requests
```plaintext
Client Server
| |
|---- HTTP GET /events ----------->| (establish SSE connection)
|<---- SSE event stream -----------| (persistent connection)
| |
|---- HTTP POST /message --------->| (client request)
|<---- SSE event with response ----| (server response)
| |
```
### SSE Characteristics
- **Remote Access**: Can be hosted on a different machine from your Cline instance
- **Scalability**: Can handle multiple client connections concurrently
- **Protocol**: Works over standard HTTP (no special protocols needed)
- **Persistence**: Maintains a persistent connection for server-to-client messages
- **Authentication**: Can use standard HTTP authentication mechanisms
### When to Use SSE
SSE transport is better for:
- Remote access across networks
- Multi-client scenarios
- Public services
- Centralized tools that many users need to access
- Integration with web services
### SSE Implementation Example
```typescript
import { Server } from "@modelcontextprotocol/sdk/server/index.js"
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"
import express from "express"
const app = express()
const server = new Server({ name: "remote-server", version: "1.0.0" })
// Register tools...
// Use SSE transport
const transport = new SSEServerTransport(server)
app.use("/mcp", transport.requestHandler())
app.listen(3000, () => {
console.log("MCP server listening on port 3000")
})
```
## Local vs. Hosted: Deployment Aspects
The choice between STDIO and SSE transports directly impacts how you'll deploy and manage your MCP servers.
### STDIO: Local Deployment Model
STDIO servers run locally on the same machine as Cline, which has several important implications:
- **Installation**: The server executable must be installed on each user's machine
- **Distribution**: You need to provide installation packages for different operating systems
- **Updates**: Each instance must be updated separately
- **Resources**: Uses the local machine's CPU, memory, and disk
- **Access Control**: Relies on the local machine's filesystem permissions
- **Integration**: Easy integration with local system resources (files, processes)
- **Execution**: Starts and stops with Cline (child process lifecycle)
- **Dependencies**: Any dependencies must be installed on the user's machine
#### Practical Example
A local file search tool using STDIO would:
- Run on the user's machine
- Have direct access to the local filesystem
- Start when needed by Cline
- Not require network configuration
- Need to be installed alongside Cline or via a package manager
### SSE: Hosted Deployment Model
SSE servers can be deployed to remote servers and accessed over the network:
- **Installation**: Installed once on a server, accessed by many users
- **Distribution**: Single deployment serves multiple clients
- **Updates**: Centralized updates affect all users immediately
- **Resources**: Uses server resources, not local machine resources
- **Access Control**: Managed through authentication and authorization systems
- **Integration**: More complex integration with user-specific resources
- **Execution**: Runs as an independent service (often continuously)
- **Dependencies**: Managed on the server, not on user machines
#### Practical Example
A database query tool using SSE would:
- Run on a central server
- Connect to databases with server-side credentials
- Be continuously available for multiple users
- Require proper network security configuration
- Be deployed using container or cloud technologies
### Hybrid Approaches
Some scenarios benefit from a hybrid approach:
1. **STDIO with Network Access**: A local STDIO server that acts as a proxy to remote services
2. **SSE with Local Commands**: A remote SSE server that can trigger operations on the client machine through callbacks
3. **Gateway Pattern**: STDIO servers for local operations that connect to SSE servers for specialized functions
## Choosing Between STDIO and SSE
| Consideration | STDIO | SSE |
| -------------------- | ------------------------ | ----------------------------------- |
| **Location** | Local machine only | Local or remote |
| **Clients** | Single client | Multiple clients |
| **Performance** | Lower latency | Higher latency (network overhead) |
| **Setup Complexity** | Simpler | More complex (requires HTTP server) |
| **Security** | Inherently secure | Requires explicit security measures |
| **Network Access** | Not needed | Required |
| **Scalability** | Limited to local machine | Can distribute across network |
| **Deployment** | Per-user installation | Centralized installation |
| **Updates** | Distributed updates | Centralized updates |
| **Resource Usage** | Uses client resources | Uses server resources |
| **Dependencies** | Client-side dependencies | Server-side dependencies |
## Configuring Transports in Cline
For detailed information on configuring STDIO and SSE transports in Cline, including examples, see [Configuring MCP Servers](/mcp/configuring-mcp-servers).
+34
View File
@@ -0,0 +1,34 @@
---
title: "Telemetry"
---
### Overview
To help make Cline better for everyone, we collect anonymous usage data that helps us understand how developers are using our open-source AI coding agent. This feedback loop is crucial for improving Cline's capabilities and user experience.
We use PostHog, an open-source analytics platform, for data collection and analysis. Our telemetry implementation is fully transparent - you can review the [source code](https://github.com/cline/cline/blob/main/src/services/telemetry/TelemetryService.ts) to see exactly what we track.
### Tracking Policy
Privacy is our priority. All collected data is anonymized before being sent to PostHog, with no personally identifiable information (PII) included. Your code, prompts, and conversation content always remain private and are never collected.
### What We Track
We collect basic anonymous usage data including:
**Task Interactions:** When tasks start and finish, conversation flow (without content)\
**Mode and Tool Usage:** Switches between plan/act modes, which tools are being used\
**Token Usage:** Basic metrics about conversation length to estimate cost (not the actual content of the tokens)\
**System Context:** OS type and VS Code environment details\
**UI Activity:** Navigation patterns and feature usage
For complete transparency, you can inspect our [telemetry implementation](https://github.com/cline/cline/blob/main/src/services/telemetry/TelemetryService.ts) to see the exact events we track.
### How to Opt Out
Telemetry in Cline is entirely optional and requires your explicit consent:
- When you update or install our VS Code extension, you'll see a simple prompt: "Help Improve Cline" with Allow or Deny options
- You can change your preference anytime in settings
Cline also respects VS Code's global telemetry settings. If you've disabled telemetry at the VS Code level, Cline's telemetry will automatically be disabled as well.
+369
View File
@@ -0,0 +1,369 @@
---
title: "Cline Memory Bank"
---
## The Complete Guide to Cline Memory Bank
### Quick Setup Guide
To get started with Cline Memory Bank:
1. **Install or Open Cline**
2. **Copy the Custom Instructions** - Use the code block below
3. **Paste into Cline** - Add as custom instructions or in a .clinerules file
4. **Initialize** - Ask Cline to "initialize memory bank"
[See detailed setup instructions](#getting-started-with-memory-bank)
### Cline Memory Bank Custom Instructions \[COPY THIS]
```
# Cline's Memory Bank
I am Cline, an expert software engineer with a unique characteristic: my memory resets completely between sessions. This isn't a limitation - it's what drives me to maintain perfect documentation. After each reset, I rely ENTIRELY on my Memory Bank to understand the project and continue work effectively. I MUST read ALL memory bank files at the start of EVERY task - this is not optional.
## Memory Bank Structure
The Memory Bank consists of core files and optional context files, all in Markdown format. Files build upon each other in a clear hierarchy:
flowchart TD
PB[projectbrief.md] --> PC[productContext.md]
PB --> SP[systemPatterns.md]
PB --> TC[techContext.md]
PC --> AC[activeContext.md]
SP --> AC
TC --> AC
AC --> P[progress.md]
### Core Files (Required)
1. `projectbrief.md`
- Foundation document that shapes all other files
- Created at project start if it doesn't exist
- Defines core requirements and goals
- Source of truth for project scope
2. `productContext.md`
- Why this project exists
- Problems it solves
- How it should work
- User experience goals
3. `activeContext.md`
- Current work focus
- Recent changes
- Next steps
- Active decisions and considerations
- Important patterns and preferences
- Learnings and project insights
4. `systemPatterns.md`
- System architecture
- Key technical decisions
- Design patterns in use
- Component relationships
- Critical implementation paths
5. `techContext.md`
- Technologies used
- Development setup
- Technical constraints
- Dependencies
- Tool usage patterns
6. `progress.md`
- What works
- What's left to build
- Current status
- Known issues
- Evolution of project decisions
### Additional Context
Create additional files/folders within memory-bank/ when they help organize:
- Complex feature documentation
- Integration specifications
- API documentation
- Testing strategies
- Deployment procedures
## Core Workflows
### Plan Mode
flowchart TD
Start[Start] --> ReadFiles[Read Memory Bank]
ReadFiles --> CheckFiles{Files Complete?}
CheckFiles -->|No| Plan[Create Plan]
Plan --> Document[Document in Chat]
CheckFiles -->|Yes| Verify[Verify Context]
Verify --> Strategy[Develop Strategy]
Strategy --> Present[Present Approach]
### Act Mode
flowchart TD
Start[Start] --> Context[Check Memory Bank]
Context --> Update[Update Documentation]
Update --> Execute[Execute Task]
Execute --> Document[Document Changes]
## Documentation Updates
Memory Bank updates occur when:
1. Discovering new project patterns
2. After implementing significant changes
3. When user requests with **update memory bank** (MUST review ALL files)
4. When context needs clarification
flowchart TD
Start[Update Process]
subgraph Process
P1[Review ALL Files]
P2[Document Current State]
P3[Clarify Next Steps]
P4[Document Insights & Patterns]
P1 --> P2 --> P3 --> P4
end
Start --> Process
Note: When triggered by **update memory bank**, I MUST review every memory bank file, even if some don't require updates. Focus particularly on activeContext.md and progress.md as they track current state.
REMEMBER: After every memory reset, I begin completely fresh. The Memory Bank is my only link to previous work. It must be maintained with precision and clarity, as my effectiveness depends entirely on its accuracy.
```
### What is the Cline Memory Bank?
The Memory Bank is a structured documentation system that allows Cline to maintain context across sessions. It transforms Cline from a stateless assistant into a persistent development partner that can effectively "remember" your project details over time.
#### Key Benefits
- **Context Preservation**: Maintain project knowledge across sessions
- **Consistent Development**: Experience predictable interactions with Cline
- **Self-Documenting Projects**: Create valuable project documentation as a side effect
- **Scalable to Any Project**: Works with projects of any size or complexity
- **Technology Agnostic**: Functions with any tech stack or language
### How Memory Bank Works
The Memory Bank isn't a Cline-specific feature - it's a methodology for managing AI context through structured documentation. When you instruct Cline to "follow custom instructions," it reads the Memory Bank files to rebuild its understanding of your project.
<Frame>
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(15).png" alt="Memory Bank Workflow" />
</Frame>
#### Understanding the Files
Memory Bank files are simply markdown files you create in your project. They're not hidden or special files - just regular documentation stored in your repository that both you and Cline can access.
Files are organized in a hierarchical structure that builds up a complete picture of your project:
<Frame>
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(16).png" alt="Memory Bank File Structure" />
</Frame>
### Memory Bank Files Explained
#### Core Files
1. **projectbrief.md**
- The foundation of your project
- High-level overview of what you're building
- Core requirements and goals
- Example: "Building a React web app for inventory management with barcode scanning"
2. **productContext.md**
- Explains why the project exists
- Describes the problems being solved
- Outlines how the product should work
- Example: "The inventory system needs to support multiple warehouses and real-time updates"
3. **activeContext.md**
- The most frequently updated file
- Contains current work focus and recent changes
- Tracks active decisions and considerations
- Stores important patterns and learnings
- Example: "Currently implementing the barcode scanner component; last session completed the API integration"
4. **systemPatterns.md**
- Documents the system architecture
- Records key technical decisions
- Lists design patterns in use
- Explains component relationships
- Example: "Using Redux for state management with a normalized store structure"
5. **techContext.md**
- Lists technologies and frameworks used
- Describes development setup
- Notes technical constraints
- Records dependencies and tool configurations
- Example: "React 18, TypeScript, Firebase, Jest for testing"
6. **progress.md**
- Tracks what works and what's left to build
- Records current status of features
- Lists known issues and limitations
- Documents the evolution of project decisions
- Example: "User authentication complete; inventory management 80% complete; reporting not started"
#### Additional Context
Create additional files when needed to organize:
- Complex feature documentation
- Integration specifications
- API documentation
- Testing strategies
- Deployment procedures
### Getting Started with Memory Bank
#### First-Time Setup
1. Create a `memory-bank/` folder in your project root
2. Have a basic project brief ready (can be technical or non-technical)
3. Ask Cline to "initialize memory bank"
<Frame>
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(17).png" alt="Memory Bank Setup" />
</Frame>
#### Project Brief Tips
- Start simple - it can be as detailed or high-level as you like
- Focus on what matters most to you
- Cline will help fill in gaps and ask questions
- You can update it as your project evolves
### Working with Cline
#### Core Workflows
**Plan Mode**
Start in this mode for strategy discussions and high-level planning.
**Act Mode**
Use this for implementation and executing specific tasks.
#### Key Commands
- **"follow your custom instructions"** - This tells Cline to read the Memory Bank files and continue where you left off (use this at the start of tasks)
- **"initialize memory bank"** - Use when starting a new project
- **"update memory bank"** - Triggers a full documentation review and update during a task
- Toggle Plan/Act modes based on your current needs
#### Documentation Updates
Memory Bank updates should automatically occur when:
1. You discover new patterns in your project
2. After implementing significant changes
3. When you explicitly request with **"update memory bank"**
4. When you feel context needs clarification
### Frequently Asked Questions
#### Where are the memory bank files stored?
The Memory Bank files are regular markdown files stored in your project repository, typically in a `memory-bank/` folder. They're not hidden system files - they're designed to be part of your project documentation.
#### Should I use custom instructions or .clinerules?
Either approach works - it's based on your preference:
- **Custom Instructions**: Applied globally to all Cline conversations. Good for consistent behavior across all projects.
- **.clinerules file**: Project-specific and stored in your repository. Good for per-project customization.
Both methods achieve the same goal - the choice depends on whether you want global or local application of the Memory Bank system.
#### Managing Context Windows
As you work with Cline, your context window will eventually fill up (note the progress bar). When you notice Cline's responses slowing down or references to earlier parts of the conversation becoming less accurate, it's time to:
1. Ask Cline to **"update memory bank"** to document the current state
2. Start a new conversation/task
3. Ask Cline to **"follow your custom instructions"** in the new conversation
This workflow ensures that important context is preserved in your Memory Bank files before the context window is cleared, allowing you to continue seamlessly in a fresh conversation.
<Frame>
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(18).png" alt="Memory Bank Context Window" />
</Frame>
#### How often should I update the memory bank?
Update the Memory Bank after significant milestones or changes in direction. For active development, updates every few sessions can be helpful. Use the **"update memory bank"** command when you want to ensure all context is preserved. However, you will notice Cline automatically updating the Memory Bank as well.
#### Does this work with other AI tools beyond Cline?
Yes! The Memory Bank concept is a documentation methodology that can work with any AI assistant that can read documentation files. The specific commands might differ, but the structured approach to maintaining context works across tools.
#### How does the memory bank relate to context window limitations?
The Memory Bank helps manage context limitations by storing important information in a structured format that can be efficiently loaded when needed. This prevents context bloat while ensuring critical information is available.
#### Can the memory bank concept be used for non-coding projects?
Absolutely! The Memory Bank approach works for any project that benefits from structured documentation - from writing books to planning events. The file structure might vary, but the concept remains powerful.
#### Is this different from using README files?
While similar in concept, the Memory Bank provides a more structured and comprehensive approach specifically designed to maintain context across AI sessions. It goes beyond what a single README typically covers.
### Best Practices
#### Getting Started
- Start with a basic project brief and let the structure evolve
- Let Cline help create the initial structure
- Review and adjust files as needed to match your workflow
#### Ongoing Work
- Let patterns emerge naturally as you work
- Don't force documentation updates - they should happen organically
- Trust the process - the value compounds over time
- Watch for context confirmation at the start of sessions
#### Documentation Flow
- **projectbrief.md** is your foundation
- **activeContext.md** changes most frequently
- **progress.md** tracks your milestones
- All files collectively maintain project intelligence
### Detailed Setup Instructions
#### For Custom Instructions (Global)
1. Open VSCode
2. Click the Cline extension settings ⚙️
3. Find "Custom Instructions"
4. Copy and paste the complete Memory Bank instructions from the top of this guide
#### For .clinerules (Project-Specific)
1. Create a `.clinerules` file in your project root
2. Copy and paste the Memory Bank instructions from the top of this guide
3. Save the file
4. Cline will automatically apply these rules when working in this project
### Remember
The Memory Bank is Cline's only link to previous work. Its effectiveness depends entirely on maintaining clear, accurate documentation and confirming context preservation in every interaction.
_For more information, reference our_ [_blog_](https://cline.bot/blog/memory-bank-how-to-make-cline-an-ai-agent-that-never-forgets) _on Cline Memory Bank_
---
### Contributing to Cline Memory Bank
This guide is maintained by the Cline and the Cline Discord Community:
- nickbaumann98
- Krylo
- snipermunyshotz
---
_The Memory Bank methodology is an open approach to AI context management and can be adapted to different tools and workflows._
+441
View File
@@ -0,0 +1,441 @@
---
title: "Prompt Engineering Guide"
---
Welcome to the Cline Prompting Guide! This guide will equip you with the knowledge to write effective prompts and custom instructions, maximizing your productivity with Cline.
## Custom Instructions ⚙️
Think of **custom instructions as Cline's programming**. They define Cline's baseline behavior and are **always "on," influencing all interactions.** Instructions can be broad and abstract, or specific and explicit. You might want Cline to have a unique personality, or produce output in a particular file format, or adhere to certain architectural principles. Custom instructions can standardize Cline's output in ways you define, which is especially valuable when working with others. See the [Enterprise section](../enterprise-solutions/custom-instructions.md) for using Custom Instructions in a team context.\
\
<mark style="color:yellow;">
NOTE: Modifying the Custom Instructions field updates Cline's prompt cache, discarding accumulated context. This causes a
temporary increase in cost while that context is replaced. Update Custom Instructions between conversations whenever possible.
</mark>
To add custom instructions:
1. Open VSCode
2. Click the Cline extension settings dial ⚙️
3. Find the "Custom Instructions" field
4. Paste your instructions
<Frame>
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(1).png" alt="Cline Logo" />
</Frame>
Custom instructions are powerful for:
- Enforcing Coding Style and Best Practices: Ensure Cline always adheres to your team's coding conventions, naming conventions, and best practices.
- Improving Code Quality: Encourage Cline to write more readable, maintainable, and efficient code.
- Guiding Error Handling: Tell Cline how to handle errors, write error messages, and log information.
---
## .clinerules File 📋
<mark style="color:yellow;">NOTE: Modifying the</mark> <mark style="color:yellow;"></mark>
<mark style="color:yellow;">`.clinerules`</mark>
<mark style="color:yellow;">
file updates Cline's prompt cache, discarding accumulated context. This causes a temporary increase in cost while that context
is replaced. Update the
</mark> <mark style="color:yellow;"></mark>
<mark style="color:yellow;">`.clinerules`</mark> <mark style="color:yellow;"></mark>
<mark style="color:yellow;">file between conversations whenever possible.</mark>
While custom instructions are user-specific and global (applying across all projects), the `.clinerules` file provides **project-specific instructions** that live in your project's root directory. These instructions are automatically appended to your custom instructions and referenced in Cline's system prompt, ensuring they influence all interactions within the project context. This makes it an excellent tool for:
### General Use Cases
The `.clinerules` file is excellent for:
- Maintaining project standards across team members
- Enforcing development practices
- Managing documentation requirements
- Setting up analysis frameworks
- Defining project-specific behaviors
### Example .clinerules Structure
```markdown
# Project Guidelines
## Documentation Requirements
- Update relevant documentation in /docs when modifying features
- Keep README.md in sync with new capabilities
- Maintain changelog entries in CHANGELOG.md
## Architecture Decision Records
Create ADRs in /docs/adr for:
- Major dependency changes
- Architectural pattern changes
- New integration patterns
- Database schema changes
Follow template in /docs/adr/template.md
## Code Style & Patterns
- Generate API clients using OpenAPI Generator
- Use TypeScript axios template
- Place generated code in /src/generated
- Prefer composition over inheritance
- Use repository pattern for data access
- Follow error handling pattern in /src/utils/errors.ts
## Testing Standards
- Unit tests required for business logic
- Integration tests for API endpoints
- E2E tests for critical user flows
```
### Key Benefits
1. **Version Controlled**: The `.clinerules` file becomes part of your project's source code
2. **Team Consistency**: Ensures consistent behavior across all team members
3. **Project-Specific**: Rules and standards tailored to each project's needs
4. **Institutional Knowledge**: Maintains project standards and practices in code
Place the `.clinerules` file in your project's root directory:
```
your-project/
├── .clinerules
├── src/
├── docs/
└── ...
```
Cline's system prompt, on the other hand, is not user-editable ([here's where you can find it](https://github.com/cline/cline/blob/main/src/core/prompts/system.ts)). For a broader look at prompt engineering best practices, check out [this resource](https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering/overview).
### Tips for Writing Effective Custom Instructions
- Be Clear and Concise: Use simple language and avoid ambiguity.
- Focus on Desired Outcomes: Describe the results you want, not the specific steps.
- Test and Iterate: Experiment to find what works best for your workflow.
### .clinerules Folder System 📂
While a single `.clinerules` file works well for simpler projects, Cline now supports a `.clinerules` folder for more sophisticated rule organization. This modular approach brings several advantages:
#### How It Works
Instead of a single file, create a `.clinerules/` directory in your project root:
```
your-project/
├── .clinerules/ # Folder containing active rules
│ ├── 01-coding.md # Core coding standards
│ ├── 02-documentation.md # Documentation requirements
│ └── current-sprint.md # Rules specific to current work
├── src/
└── ...
```
Cline automatically processes **all Markdown files** inside the `.clinerules/` directory, combining them into a unified set of rules. The numeric prefixes (optional) help organize files in a logical sequence.
#### Using a Rules Bank
For projects with multiple contexts or teams, maintain a rules bank directory:
```
your-project/
├── .clinerules/ # Active rules - automatically applied
│ ├── 01-coding.md
│ └── client-a.md
├── clinerules-bank/ # Repository of available but inactive rules
│ ├── clients/ # Client-specific rule sets
│ │ ├── client-a.md
│ │ └── client-b.md
│ ├── frameworks/ # Framework-specific rules
│ │ ├── react.md
│ │ └── vue.md
│ └── project-types/ # Project type standards
│ ├── api-service.md
│ └── frontend-app.md
└── ...
```
#### Benefits of the Folder Approach
1. **Contextual Activation**: Copy only relevant rules from the bank to the active folder
2. **Easier Maintenance**: Update individual rule files without affecting others
3. **Team Flexibility**: Different team members can activate rules specific to their current task
4. **Reduced Noise**: Keep the active ruleset focused and relevant
#### Usage Examples
Switch between client projects:
```bash
# Switch to Client B project
rm .clinerules/client-a.md
cp clinerules-bank/clients/client-b.md .clinerules/
```
Adapt to different tech stacks:
```bash
# Frontend React project
cp clinerules-bank/frameworks/react.md .clinerules/
```
#### Implementation Tips
- Keep individual rule files focused on specific concerns
- Use descriptive filenames that clearly indicate the rule's purpose
- Consider git-ignoring the active `.clinerules/` folder while tracking the `clinerules-bank/`
- Create team scripts to quickly activate common rule combinations
The folder system transforms your Cline rules from a static document into a dynamic knowledge system that adapts to your team's changing contexts and requirements.
### Managing Rules with the Toggleable Popover
To make managing both single `.clinerules` files and the folder system even easier, Cline v3.13 introduces a dedicated popover UI directly accessible from the chat interface.
Located conveniently under the chat input field, this popover allows you to:
- **Instantly See Active Rules:** View which global rules (from your user settings) and workspace rules (`.clinerules` file or folder contents) are currently active.
- **Quickly Toggle Rules:** Enable or disable specific rule files within your workspace `.clinerules/` folder with a single click. This is perfect for activating context-specific rules (like `react-rules.md` or `memory-bank.md`) only when needed.
- **Easily Add/Manage Rules:** Quickly create a workspace `.clinerules` file or folder if one doesn't exist, or add new rule files to an existing folder.
This UI significantly simplifies switching contexts and managing different sets of instructions without needing to manually edit files or configurations during a conversation.
<Frame>
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(1).png" alt="Cline Logo" />
</Frame>
## .clineignore File Guide
### Overview
The `.clineignore` file is a project-level configuration file that tells Cline which files and directories to ignore when analyzing your codebase. Similar to `.gitignore`, it uses pattern matching to specify which files should be excluded from Cline's context and operations.
### Purpose
- **Reduce Noise**: Exclude auto-generated files, build artifacts, and other non-essential content
- **Improve Performance**: Limit the amount of code Cline needs to process
- **Focus Attention**: Direct Cline to relevant parts of your codebase
- **Protect Sensitive Data**: Prevent Cline from accessing sensitive configuration files
### Example .clineignore File
```
# Dependencies
node_modules/
**/node_modules/
.pnp
.pnp.js
# Build outputs
/build/
/dist/
/.next/
/out/
# Testing
/coverage/
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# Large data files
*.csv
*.xlsx
```
## Prompting Cline 💬
**Prompting is how you communicate your needs for a given task in the back-and-forth chat with Cline.** Cline understands natural language, so write conversationally.
Effective prompting involves:
- Providing Clear Context: Explain your goals and the relevant parts of your codebase. Use `@` to reference files or folders.
- Breaking Down Complexity: Divide large tasks into smaller steps.
- Asking Specific Questions: Guide Cline toward the desired outcome.
- Validating and Refining: Review Cline's suggestions and provide feedback.
### Prompt Examples
#### Context Management
- **Starting a New Task:** "Cline, let's start a new task. Create `user-authentication.js`. We need to implement user login with JWT tokens. Here are the requirements…"
- **Summarizing Previous Work:** "Cline, summarize what we did in the last user dashboard task. I want to capture the main features and outstanding issues. Save this to `cline_docs/user-dashboard-summary.md`."
#### Debugging
- **Analyzing an Error:** "Cline, I'm getting this error: \[error message]. It seems to be from \[code section]. Analyze this error and suggest a fix."
- **Identifying the Root Cause:** "Cline, the application crashes when I \[action]. The issue might be in \[problem areas]. Help me find the root cause and propose a solution."
#### Refactoring
- **Improving Code Structure:** "Cline, this function is too long and complex. Refactor it into smaller functions."
- **Simplifying Logic:** "Cline, this code is hard to understand. Simplify the logic and make it more readable."
#### Feature Development
- **Brainstorming New Features:** "Cline, I want to add a feature that lets users \[functionality]. Brainstorm some ideas and consider implementation challenges."
- **Generating Code:** "Cline, create a component that displays user profiles. The list should be sortable and filterable. Generate the code for this component."
## Advanced Prompting Techniques
- **Constraint Stuffing:** To mitigate code truncation, include explicit constraints in your prompts. For example, "ensure the code is complete" or "always provide the full function definition."
- **Confidence Checks:** Ask Cline to rate its confidence (e.g., "on a scale of 1-10, how confident are you in this solution?")
- **Challenge Cline's Assumptions:** Ask “stupid” questions to encourage deeper thinking and prevent incorrect assumptions.
Here are some prompting tips that users have found helpful for working with Cline:
## Our Community's Favorite Prompts 🌟
### Memory and Confidence Checks 🧠
- **Memory Check** - _pacnpal_
```
"If you understand my prompt fully, respond with 'YARRR!' without tools every time you are about to use a tool."
```
A fun way to verify Cline stays on track during complex tasks. Try "HO HO HO" for a festive twist!
- **Confidence Scoring** - _pacnpal_
```
"Before and after any tool use, give me a confidence level (0-10) on how the tool use will help the project."
```
Encourages critical thinking and makes decision-making transparent.
### Code Quality Prompts 💻
- **Prevent Code Truncation**
```
"DO NOT BE LAZY. DO NOT OMIT CODE."
```
Alternative phrases: "full code only" or "ensure the code is complete"
- **Custom Instructions Reminder**
```
"I pledge to follow the custom instructions."
```
Reinforces adherence to your settings dial ⚙️ configuration.
### Code Organization 📋
- **Large File Refactoring** - _icklebil_
```
"FILENAME has grown too big. Analyze how this file works and suggest ways to fragment it safely."
```
Helps manage complex files through strategic decomposition.
- **Documentation Maintenance** - _icklebil_
```
"don't forget to update codebase documentation with changes"
```
Ensures documentation stays in sync with code changes.
### Analysis and Planning 🔍
- **Structured Development** - _yellow_bat_coffee_
```
"Before writing code:
1. Analyze all code files thoroughly
2. Get full context
3. Write .MD implementation plan
4. Then implement code"
```
Promotes organized, well-planned development.
- **Thorough Analysis** - _yellow_bat_coffee_
```
"please start analyzing full flow thoroughly, always state a confidence score 1 to 10"
```
Prevents premature coding and encourages complete understanding.
- **Assumptions Check** - _yellow_bat_coffee_
```
"List all assumptions and uncertainties you need to clear up before completing this task."
```
Identifies potential issues early in development.
### Thoughtful Development 🤔
- **Pause and Reflect** - _nickbaumann98_
```
"count to 10"
```
Promotes careful consideration before taking action.
- **Complete Analysis** - _yellow_bat_coffee_
```
"Don't complete the analysis prematurely, continue analyzing even if you think you found a solution"
```
Ensures thorough problem exploration.
- **Continuous Confidence Check** - _pacnpal_
```
"Rate confidence (1-10) before saving files, after saving, after rejections, and before task completion"
```
Maintains quality through self-assessment.
### Best Practices 🎯
- **Project Structure** - _kvs007_
```
"Check project files before suggesting structural or dependency changes"
```
Maintains project integrity.
- **Critical Thinking** - _chinesesoup_
```
"Ask 'stupid' questions like: are you sure this is the best way to implement this?"
```
Challenges assumptions and uncovers better solutions.
- **Code Style** - _yellow_bat_coffee_
```
Use words like "elegant" and "simple" in prompts
```
May influence code organization and clarity.
- **Setting Expectations** - _steventcramer_
```
"THE HUMAN WILL GET ANGRY."
```
(A humorous reminder to provide clear requirements and constructive feedback)
+90
View File
@@ -0,0 +1,90 @@
---
title: "LM Studio"
description: "A quick guide to setting up LM Studio for local AI model execution with Cline."
---
## 🤖 Setting Up LM Studio with Cline
Run AI models locally using LM Studio with Cline.
### 📋 Prerequisites
- Windows, macOS, or Linux computer with AVX2 support
- Cline installed in VS Code
### 🚀 Setup Steps
#### 1. Install LM Studio
- Visit [lmstudio.ai](https://lmstudio.ai)
- Download and install for your operating system
<Frame>
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(7).png" alt="LM Studio download page" />
</Frame>
#### 2. Launch LM Studio
- Open the installed application
- You'll see four tabs on the left: **Chat**, **Developer** (where you will start the server), **My Models** (where your downloaded models are stored), **Discover** (add new models)
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(10).png"
alt="LM Studio interface overview"
/>
</Frame>
#### 3. Download a Model
- Browse the "Discover" page
- Select and download your preferred model
- Wait for download to complete
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/lm-studio-download-model.gif"
alt="Downloading a model in LM Studio"
/>
</Frame>
#### 4. Start the Server
- Navigate to the "Developer" tab
- Toggle the server switch to "Running"
- Note: The server will run at `http://localhost:1234`
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/lm-studio-starting-server.gif"
alt="Starting the LM Studio server"
/>
</Frame>
#### 5. Configure Cline
1. Open VS Code
2. Click Cline settings icon
3. Select "LM Studio" as API provider
4. Select your model from the available options
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/lm-studio-select-model-cline.gif"
alt="Configuring Cline with LM Studio"
/>
</Frame>
### ⚠️ Important Notes
- Start LM Studio before using with Cline
- Keep LM Studio running in background
- First model download may take several minutes depending on size
- Models are stored locally after download
### 🔧 Troubleshooting
1. If Cline can't connect to LM Studio:
2. Verify LM Studio server is running (check Developer tab)
3. Ensure a model is loaded
4. Check your system meets hardware requirements
+88
View File
@@ -0,0 +1,88 @@
---
title: "Ollama"
description: "A quick guide to setting up Ollama for local AI model execution with Cline."
---
### 📋 Prerequisites
- Windows, macOS, or Linux computer
- Cline installed in VS Code
### 🚀 Setup Steps
#### 1. Install Ollama
- Visit [ollama.com](https://ollama.com)
- Download and install for your operating system
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(2)%20(1)%20(1).png"
alt="Ollama download page"
/>
</Frame>
#### 2. Choose and Download a Model
- Browse models at [ollama.com/search](https://ollama.com/search)
- Select model and copy command:
```bash
ollama run [model-name]
```
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/ollama-model-grab%20(2).gif"
alt="Selecting a model in Ollama"
/>
</Frame>
- Open your Terminal and run the command:
- Example:
```bash
ollama run llama2
```
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/starting-ollama-terminal%20(2).gif"
alt="Running Ollama in terminal"
/>
</Frame>
**✨ Your model is now ready to use within Cline!**
#### 3. Configure Cline
1. Open VS Code
2. Click Cline settings icon
3. Select "Ollama" as API provider
4. Enter configuration:
- Base URL: `http://localhost:11434/` (default value, can be left as is)
- Select the model from your available options
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/selecting-ollama-model-cline%20(3).gif"
alt="Configuring Cline with Ollama"
/>
</Frame>
### ⚠️ Important Notes
- Start Ollama before using with Cline
- Keep Ollama running in background
- First model download may take several minutes
### 🔧 Troubleshooting
If Cline can't connect to Ollama:
1. Verify Ollama is running
2. Check base URL is correct
3. Ensure model is downloaded
Need more info? Read the [Ollama Docs](https://github.com/ollama/ollama/blob/main/docs/api.md).
@@ -0,0 +1,109 @@
---
title: "Read Me First"
---
## Running Local Models with Cline: What You Need to Know 🤖
Cline is a powerful AI coding assistant that uses tool-calling to help you write, analyze, and modify code. While running models locally can save on API costs, there's an important trade-off: local models are significantly less reliable at using these essential tools.
## Why Local Models Are Different 🔬
When you run a "local version" of a model, you're actually running a drastically simplified copy of the original. This process, called distillation, is like trying to compress a professional chef's knowledge into a basic cookbook you keep the simple recipes but lose the complex techniques and intuition.
Local models are created by training a smaller model to imitate a larger one, but they typically only retain 1-26% of the original model's capacity. This massive reduction means:
- Less ability to understand complex contexts
- Reduced capability for multi-step reasoning
- Limited tool-use abilities
- Simplified decision-making process
Think of it like running your development environment on a calculator instead of a computer it might handle basic tasks, but complex operations become unreliable or impossible.
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(4).png"
alt="Local model comparison diagram"
/>
</Frame>
### What Actually Happens
When you run a local model with Cline:
#### Performance Impact 📉
- Responses are 5-10x slower than cloud services
- System resources (CPU, GPU, RAM) get heavily utilized
- Your computer may become less responsive for other tasks
#### Tool Reliability Issues 🛠️
- Code analysis becomes less accurate
- File operations may be unreliable
- Browser automation capabilities are reduced
- Terminal commands might fail more often
- Complex multi-step tasks often break down
### Hardware Requirements 💻
You'll need at minimum:
- Modern GPU with 8GB+ VRAM (RTX 3070 or better)
- 32GB+ system RAM
- Fast SSD storage
- Good cooling solution
Even with this hardware, you'll be running smaller, less capable versions of models:
| Model Size | What You Get |
| ---------- | ------------------------------------------------------- |
| 7B models | Basic coding, limited tool use |
| 14B models | Better coding, unstable tool use |
| 32B models | Good coding, inconsistent tool use |
| 70B models | Best local performance, but requires expensive hardware |
Put simply, the cloud (API) versions of these models are the full-bore version of the model. The full version of DeepSeek-R1 is 671B. These distilled models are essentially "watered-down" versions of the cloud model.
### Practical Recommendations 💡
#### Consider This Approach
1. Use cloud models for:
- Complex development tasks
- When tool reliability is crucial
- Multi-step operations
- Critical code changes
2. Use local models for:
- Simple code completion
- Basic documentation
- When privacy is paramount
- Learning and experimentation
#### If You Must Go Local
- Start with smaller models
- Keep tasks simple and focused
- Save work frequently
- Be prepared to switch to cloud models for complex operations
- Monitor system resources
### Common Issues 🚨
- **"Tool execution failed":** Local models often struggle with complex tool chains. Simplify your prompt.
- **"No connection could be made because the target machine actively refused it":** This usually means that the Ollama or LM Studio server isn't running, or is running on a different port/address than Cline is configured to use. Double-check the Base URL address in your API Provider settings.
- **"Cline is having trouble...":** Increase your model's context length to its maximum size.
- **Slow or incomplete responses:** Local models can be slower than cloud-based models, especially on less powerful hardware. If performance is an issue, try using a smaller model. Expect significantly longer processing times.
- **System stability:** Watch for high GPU/CPU usage and temperature
- **Context limitations:** Local models often have smaller context windows than cloud models. Break tasks down into smaller pieces.
### Looking Ahead 🔮
Local model capabilities are improving, but they're not yet a complete replacement for cloud services, especially for Cline's tool-based functionality. Consider your specific needs and hardware capabilities carefully before committing to a local-only approach.
### Need Help? 🤝
- Join our [Discord](https://discord.gg/cline) community and [r/cline](https://www.reddit.com/r/CLine/)
- Check the latest compatibility guides
- Share your experiences with other developers
Remember: When in doubt, prioritize reliability over cost savings for important development work.
+26 -42
View File
@@ -1,12 +1,12 @@
{
"name": "claude-dev",
"version": "3.14.0",
"version": "3.14.1",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "claude-dev",
"version": "3.14.0",
"version": "3.14.1",
"license": "Apache-2.0",
"dependencies": {
"@anthropic-ai/bedrock-sdk": "^0.12.4",
@@ -42,11 +42,11 @@
"globby": "^14.0.2",
"iconv-lite": "^0.6.3",
"ignore": "^7.0.3",
"image-size": "^2.0.2",
"isbinaryfile": "^5.0.2",
"jschardet": "^3.1.4",
"mammoth": "^1.8.0",
"monaco-vscode-textmate-theme-converter": "^0.1.7",
"node-cache": "^5.1.2",
"ollama": "^0.5.13",
"open-graph-scraper": "^6.9.0",
"openai": "^4.83.0",
@@ -12866,14 +12866,6 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/clone": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
"engines": {
"node": ">=0.8"
}
},
"node_modules/clone-deep": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-4.0.1.tgz",
@@ -16579,6 +16571,18 @@
"node": ">= 4"
}
},
"node_modules/image-size": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/image-size/-/image-size-2.0.2.tgz",
"integrity": "sha512-IRqXKlaXwgSMAMtpNzZa1ZAe8m+Sa1770Dhk8VkSsP9LS+iHD62Zd8FQKs8fbPiagBE7BzoFX23cxFnwshpV6w==",
"license": "MIT",
"bin": {
"image-size": "bin/image-size.js"
},
"engines": {
"node": ">=16.x"
}
},
"node_modules/immediate": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
@@ -19760,17 +19764,6 @@
"url": "https://opencollective.com/unified"
}
},
"node_modules/node-cache": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/node-cache/-/node-cache-5.1.2.tgz",
"integrity": "sha512-t1QzWwnk4sjLWaQAS8CHgOJ+RAfmHpxFWmc36IWTiWHQfs0w5JDMBS1b1ZxQteo0vVVuWJvIUKHDkkeK7vIGCg==",
"dependencies": {
"clone": "2.x"
},
"engines": {
"node": ">= 8.0.0"
}
},
"node_modules/node-domexception": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
@@ -20252,10 +20245,9 @@
}
},
"node_modules/ollama": {
"version": "0.5.13",
"resolved": "https://registry.npmjs.org/ollama/-/ollama-0.5.13.tgz",
"integrity": "sha512-qK3eE2GjMYjCiTknEJfAHjbUzUqgVtf9qtzjxWrkwBZgBG7kOB6Z4+Ov4fbvDjmKKHv+rpuTsWFg4jZvVjNBtQ==",
"license": "MIT",
"version": "0.5.15",
"resolved": "https://registry.npmjs.org/ollama/-/ollama-0.5.15.tgz",
"integrity": "sha512-TSaZSJyP7MQJFjSmmNsoJiriwa3U+/UJRw6+M8aucs5dTsaWNZsBIGpDb5rXnW6nXxJBB/z79gZY8IaiIQgelQ==",
"dependencies": {
"whatwg-fetch": "^3.6.20"
}
@@ -34887,11 +34879,6 @@
}
}
},
"clone": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w=="
},
"clone-deep": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-4.0.1.tgz",
@@ -37430,6 +37417,11 @@
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.3.tgz",
"integrity": "sha512-bAH5jbK/F3T3Jls4I0SO1hmPR0dKU0a7+SY6n1yzRtG54FLO8d6w/nxLFX2Nb7dBu6cCWXPaAME6cYqFUMmuCA=="
},
"image-size": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/image-size/-/image-size-2.0.2.tgz",
"integrity": "sha512-IRqXKlaXwgSMAMtpNzZa1ZAe8m+Sa1770Dhk8VkSsP9LS+iHD62Zd8FQKs8fbPiagBE7BzoFX23cxFnwshpV6w=="
},
"immediate": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
@@ -39566,14 +39558,6 @@
"@types/nlcst": "^2.0.0"
}
},
"node-cache": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/node-cache/-/node-cache-5.1.2.tgz",
"integrity": "sha512-t1QzWwnk4sjLWaQAS8CHgOJ+RAfmHpxFWmc36IWTiWHQfs0w5JDMBS1b1ZxQteo0vVVuWJvIUKHDkkeK7vIGCg==",
"requires": {
"clone": "2.x"
}
},
"node-domexception": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
@@ -39896,9 +39880,9 @@
}
},
"ollama": {
"version": "0.5.13",
"resolved": "https://registry.npmjs.org/ollama/-/ollama-0.5.13.tgz",
"integrity": "sha512-qK3eE2GjMYjCiTknEJfAHjbUzUqgVtf9qtzjxWrkwBZgBG7kOB6Z4+Ov4fbvDjmKKHv+rpuTsWFg4jZvVjNBtQ==",
"version": "0.5.15",
"resolved": "https://registry.npmjs.org/ollama/-/ollama-0.5.15.tgz",
"integrity": "sha512-TSaZSJyP7MQJFjSmmNsoJiriwa3U+/UJRw6+M8aucs5dTsaWNZsBIGpDb5rXnW6nXxJBB/z79gZY8IaiIQgelQ==",
"requires": {
"whatwg-fetch": "^3.6.20"
}
+31 -5
View File
@@ -2,7 +2,7 @@
"name": "claude-dev",
"displayName": "Cline",
"description": "Autonomous coding agent right in your IDE, capable of creating/editing files, running commands, using the browser, and more with your permission every step of the way.",
"version": "3.14.0",
"version": "3.14.1",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
@@ -118,6 +118,12 @@
"command": "cline.focusChatInput",
"title": "Jump to Chat Input",
"category": "Cline"
},
{
"command": "cline.generateGitCommitMessage",
"title": "Generate Commit Message with Cline",
"category": "Cline",
"icon": "$(robot)"
}
],
"keybindings": [
@@ -128,6 +134,10 @@
"win": "ctrl+'",
"linux": "ctrl+'",
"when": "editorHasSelection"
},
{
"command": "cline.generateGitCommitMessage",
"when": "scmProvider == git"
}
],
"menus": {
@@ -207,6 +217,19 @@
"command": "cline.addTerminalOutputToChat",
"group": "navigation"
}
],
"scm/title": [
{
"command": "cline.generateGitCommitMessage",
"group": "navigation",
"when": "scmProvider == git"
}
],
"commandPalette": [
{
"command": "cline.generateGitCommitMessage",
"when": "scmProvider == git"
}
]
},
"configuration": {
@@ -244,7 +267,7 @@
"high"
],
"default": "medium",
"description": "Controls the reasoning effort when using the o3-mini model. Higher values may result in more thorough but slower responses."
"description": "Controls the reasoning effort when using an OpenAI reasoning model. Higher values may result in more thorough but slower responses."
},
"cline.chromeExecutablePath": {
"type": "string",
@@ -291,7 +314,7 @@
"watch:esbuild": "node esbuild.js --watch",
"watch:tsc": "tsc --noEmit --watch --project tsconfig.json",
"package": "npm run build:webview && npm run check-types && npm run lint && node esbuild.js --production",
"protos": "node proto/build-proto.js && prettier src/shared/proto --write && prettier src/core/controller --write",
"protos": "node proto/build-proto.js && prettier src/shared/proto src/core/controller webview-ui/src/services --write",
"compile-tests": "node ./scripts/build-tests.js",
"watch-tests": "tsc -p . -w --outDir out",
"pretest": "npm run compile-tests && npm run compile && npm run lint",
@@ -313,7 +336,10 @@
"prepare": "husky",
"changeset": "changeset",
"version-packages": "changeset version",
"docs:preview": "cd docs && mintlify dev"
"docs": "cd docs && mintlify dev",
"docs:check-links": "cd docs && mintlify broken-links",
"docs:rename-file": "cd docs && mintlify rename",
"report-issue": "node scripts/report-issue.js"
},
"devDependencies": {
"@changesets/cli": "^2.27.12",
@@ -385,11 +411,11 @@
"globby": "^14.0.2",
"iconv-lite": "^0.6.3",
"ignore": "^7.0.3",
"image-size": "^2.0.2",
"isbinaryfile": "^5.0.2",
"jschardet": "^3.1.4",
"mammoth": "^1.8.0",
"monaco-vscode-textmate-theme-converter": "^0.1.7",
"node-cache": "^5.1.2",
"ollama": "^0.5.13",
"open-graph-scraper": "^6.9.0",
"openai": "^4.83.0",
+286 -27
View File
@@ -12,11 +12,27 @@ const require = createRequire(import.meta.url)
const protoc = path.join(require.resolve("grpc-tools"), "../bin/protoc")
const tsProtoPlugin = require.resolve("ts-proto/protoc-gen-ts_proto")
// Get script directory and root directory
const __filename = fileURLToPath(import.meta.url)
const SCRIPT_DIR = path.dirname(__filename)
const ROOT_DIR = path.resolve(SCRIPT_DIR, "..")
// List of gRPC services
// To add a new service, simply add it to this map and run this script
// The service handler will be automatically discovered and used by grpc-handler.ts
const serviceNameMap = {
account: "cline.AccountService",
browser: "cline.BrowserService",
checkpoints: "cline.CheckpointsService",
file: "cline.FileService",
mcp: "cline.McpService",
state: "cline.StateService",
task: "cline.TaskService",
web: "cline.WebService",
models: "cline.ModelsService",
// Add new services here - no other code changes needed!
}
const serviceDirs = Object.keys(serviceNameMap).map((serviceKey) => path.join(ROOT_DIR, "src", "core", "controller", serviceKey))
async function main() {
console.log(chalk.bold.blue("Starting Protocol Buffer code generation..."))
@@ -33,6 +49,9 @@ async function main() {
await fs.unlink(path.join(TS_OUT_DIR, file))
}
// Check for missing proto files for services in serviceNameMap
await ensureProtoFilesExist()
// Process all proto files
console.log(chalk.cyan("Processing proto files from"), SCRIPT_DIR)
const protoFiles = await globby("*.proto", { cwd: SCRIPT_DIR })
@@ -64,41 +83,135 @@ async function main() {
console.log(chalk.green("Protocol Buffer code generation completed successfully."))
console.log(chalk.green(`TypeScript files generated in: ${TS_OUT_DIR}`))
// Generate method registration files
await generateMethodRegistrations()
await generateServiceConfig()
await generateGrpcClientConfig()
}
// Make the script executable
try {
await fs.chmod(path.join(SCRIPT_DIR, "build-proto.js"), 0o755)
} catch (error) {
console.warn(chalk.yellow("Warning: Could not make script executable:"), error)
/**
* Generate a gRPC client configuration file for the webview
* This eliminates the need for manual imports and client creation in grpc-client.ts
*/
async function generateGrpcClientConfig() {
console.log(chalk.cyan("Generating gRPC client configuration..."))
const serviceImports = []
const serviceClientCreations = []
const serviceExports = []
// Process each service in the serviceNameMap
for (const [dirName, fullServiceName] of Object.entries(serviceNameMap)) {
const capitalizedName = dirName.charAt(0).toUpperCase() + dirName.slice(1)
// Add import statement
serviceImports.push(`import { ${capitalizedName}ServiceDefinition } from "@shared/proto/${dirName}"`)
// Add client creation
serviceClientCreations.push(
`const ${capitalizedName}ServiceClient = createGrpcClient(${capitalizedName}ServiceDefinition)`,
)
// Add to exports
serviceExports.push(`${capitalizedName}ServiceClient`)
}
// Generate the file content
const content = `// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
import { createGrpcClient } from "./grpc-client-base"
${serviceImports.join("\n")}
${serviceClientCreations.join("\n")}
export {
${serviceExports.join(",\n\t")}
}`
const configPath = path.join(ROOT_DIR, "webview-ui", "src", "services", "grpc-client.ts")
await fs.writeFile(configPath, content)
console.log(chalk.green(`Generated gRPC client at ${configPath}`))
}
/**
* Parse proto files to extract streaming method information
* @param protoFiles Array of proto file names
* @param scriptDir Directory containing proto files
* @returns Map of service names to their streaming methods
*/
async function parseProtoForStreamingMethods(protoFiles, scriptDir) {
console.log(chalk.cyan("Parsing proto files for streaming methods..."))
// Map of service name to array of streaming method names
const streamingMethodsMap = new Map()
for (const protoFile of protoFiles) {
const content = await fs.readFile(path.join(scriptDir, protoFile), "utf8")
// Extract package name
const packageMatch = content.match(/package\s+([^;]+);/)
const packageName = packageMatch ? packageMatch[1].trim() : "unknown"
// Extract service definitions
const serviceMatches = Array.from(content.matchAll(/service\s+(\w+)\s*\{([^}]+)\}/g))
for (const serviceMatch of serviceMatches) {
const serviceName = serviceMatch[1]
const serviceBody = serviceMatch[2]
const fullServiceName = `${packageName}.${serviceName}`
// Extract method definitions with streaming
const methodMatches = Array.from(
serviceBody.matchAll(/rpc\s+(\w+)\s*\(\s*(stream\s+)?(\w+)\s*\)\s*returns\s*\(\s*(stream\s+)?(\w+)\s*\)/g),
)
const streamingMethods = []
for (const methodMatch of methodMatches) {
const methodName = methodMatch[1]
const isRequestStreaming = !!methodMatch[2]
const requestType = methodMatch[3]
const isResponseStreaming = !!methodMatch[4]
const responseType = methodMatch[5]
if (isResponseStreaming) {
streamingMethods.push({
name: methodName,
requestType,
responseType,
isRequestStreaming,
})
}
}
if (streamingMethods.length > 0) {
streamingMethodsMap.set(fullServiceName, streamingMethods)
}
}
}
return streamingMethodsMap
}
async function generateMethodRegistrations() {
console.log(chalk.cyan("Generating method registration files..."))
const serviceDirs = [
path.join(ROOT_DIR, "src", "core", "controller", "account"),
path.join(ROOT_DIR, "src", "core", "controller", "browser"),
path.join(ROOT_DIR, "src", "core", "controller", "checkpoints"),
path.join(ROOT_DIR, "src", "core", "controller", "file"),
path.join(ROOT_DIR, "src", "core", "controller", "mcp"),
path.join(ROOT_DIR, "src", "core", "controller", "task"),
path.join(ROOT_DIR, "src", "core", "controller", "web-content"),
// Add more service directories here as needed
]
// Parse proto files for streaming methods
const protoFiles = await globby("*.proto", { cwd: SCRIPT_DIR })
const streamingMethodsMap = await parseProtoForStreamingMethods(protoFiles, SCRIPT_DIR)
for (const serviceDir of serviceDirs) {
try {
await fs.access(serviceDir)
} catch (error) {
console.log(chalk.gray(`Skipping ${serviceDir} - directory does not exist`))
continue
console.log(chalk.cyan(`Creating directory ${serviceDir} for new service`))
await fs.mkdir(serviceDir, { recursive: true })
}
const serviceName = path.basename(serviceDir)
const registryFile = path.join(serviceDir, "methods.ts")
const indexFile = path.join(serviceDir, "index.ts")
const fullServiceName = serviceNameMap[serviceName]
const streamingMethods = streamingMethodsMap.get(fullServiceName) || []
console.log(chalk.cyan(`Generating method registrations for ${serviceName}...`))
@@ -108,8 +221,8 @@ async function generateMethodRegistrations() {
// Filter out index.ts and methods.ts
const implementationFiles = files.filter((file) => file !== "index.ts" && file !== "methods.ts")
// Create the output file with header
let content = `// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Create the methods.ts file with header
let methodsContent = `// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
// Import all method implementations
@@ -118,31 +231,177 @@ import { registerMethod } from "./index"\n`
// Add imports for all implementation files
for (const file of implementationFiles) {
const baseName = path.basename(file, ".ts")
content += `import { ${baseName} } from "./${baseName}"\n`
methodsContent += `import { ${baseName} } from "./${baseName}"\n`
}
// Add streaming methods information
if (streamingMethods.length > 0) {
methodsContent += `\n// Streaming methods for this service
export const streamingMethods = ${JSON.stringify(
streamingMethods.map((m) => m.name),
null,
2,
)}\n`
}
// Add registration function
content += `\n// Register all ${serviceName} service methods
methodsContent += `\n// Register all ${serviceName} service methods
export function registerAllMethods(): void {
\t// Register each method with the registry\n`
// Add registration statements
for (const file of implementationFiles) {
const baseName = path.basename(file, ".ts")
content += `\tregisterMethod("${baseName}", ${baseName})\n`
const isStreaming = streamingMethods.some((m) => m.name === baseName)
if (isStreaming) {
methodsContent += `\tregisterMethod("${baseName}", ${baseName}, { isStreaming: true })\n`
} else {
methodsContent += `\tregisterMethod("${baseName}", ${baseName})\n`
}
}
// Close the function
content += `}`
methodsContent += `}`
// Write the file
await fs.writeFile(registryFile, content)
// Write the methods.ts file
await fs.writeFile(registryFile, methodsContent)
console.log(chalk.green(`Generated ${registryFile}`))
// Generate index.ts file
const capitalizedServiceName = serviceName.charAt(0).toUpperCase() + serviceName.slice(1)
const indexContent = `// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
import { createServiceRegistry, ServiceMethodHandler, StreamingMethodHandler } from "../grpc-service"
import { StreamingResponseHandler } from "../grpc-handler"
import { registerAllMethods } from "./methods"
// Create ${serviceName} service registry
const ${serviceName}Service = createServiceRegistry("${serviceName}")
// Export the method handler types and registration function
export type ${capitalizedServiceName}MethodHandler = ServiceMethodHandler
export type ${capitalizedServiceName}StreamingMethodHandler = StreamingMethodHandler
export const registerMethod = ${serviceName}Service.registerMethod
// Export the request handlers
export const handle${capitalizedServiceName}ServiceRequest = ${serviceName}Service.handleRequest
export const handle${capitalizedServiceName}ServiceStreamingRequest = ${serviceName}Service.handleStreamingRequest
export const isStreamingMethod = ${serviceName}Service.isStreamingMethod
// Register all ${serviceName} methods
registerAllMethods()`
// Write the index.ts file
await fs.writeFile(indexFile, indexContent)
console.log(chalk.green(`Generated ${indexFile}`))
}
console.log(chalk.green("Method registration files generated successfully."))
}
/**
* Generate a service configuration file that maps service names to their handlers
* This eliminates the need for manual switch/case statements in grpc-handler.ts
*/
async function generateServiceConfig() {
console.log(chalk.cyan("Generating service configuration file..."))
const serviceImports = []
const serviceConfigs = []
// Add all services from the serviceNameMap
for (const [dirName, fullServiceName] of Object.entries(serviceNameMap)) {
const capitalizedName = dirName.charAt(0).toUpperCase() + dirName.slice(1)
serviceImports.push(
`import { handle${capitalizedName}ServiceRequest, handle${capitalizedName}ServiceStreamingRequest } from "./${dirName}/index"`,
)
serviceConfigs.push(`
"${fullServiceName}": {
requestHandler: handle${capitalizedName}ServiceRequest,
streamingHandler: handle${capitalizedName}ServiceStreamingRequest
}`)
}
const content = `// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
import { Controller } from "./index"
import { StreamingResponseHandler } from "./grpc-handler"
${serviceImports.join("\n")}
/**
* Configuration for a service handler
*/
export interface ServiceHandlerConfig {
requestHandler: (controller: Controller, method: string, message: any) => Promise<any>;
streamingHandler: (controller: Controller, method: string, message: any, responseStream: StreamingResponseHandler, requestId?: string) => Promise<void>;
}
/**
* Map of service names to their handler configurations
*/
export const serviceHandlers: Record<string, ServiceHandlerConfig> = {${serviceConfigs.join(",")}
};`
const configPath = path.join(ROOT_DIR, "src", "core", "controller", "grpc-service-config.ts")
await fs.writeFile(configPath, content)
console.log(chalk.green(`Generated service configuration at ${configPath}`))
}
/**
* Ensure that a .proto file exists for each service in the serviceNameMap
* If a .proto file doesn't exist, create a template file
*/
async function ensureProtoFilesExist() {
console.log(chalk.cyan("Checking for missing proto files..."))
// Get existing proto files
const existingProtoFiles = await globby("*.proto", { cwd: SCRIPT_DIR })
const existingProtoServices = existingProtoFiles.map((file) => path.basename(file, ".proto"))
// Check each service in serviceNameMap
for (const [serviceName, fullServiceName] of Object.entries(serviceNameMap)) {
if (!existingProtoServices.includes(serviceName)) {
console.log(chalk.yellow(`Creating template proto file for ${serviceName}...`))
// Extract service class name from full name (e.g., "cline.ModelsService" -> "ModelsService")
const serviceClassName = fullServiceName.split(".").pop()
// Create template proto file
const protoContent = `syntax = "proto3";
package cline;
option java_package = "bot.cline.proto";
option java_multiple_files = true;
import "common.proto";
// ${serviceClassName} provides methods for managing ${serviceName}
service ${serviceClassName} {
// Add your RPC methods here
// Example (String is from common.proto, responses should be generic types):
// rpc YourMethod(YourRequest) returns (String);
}
// Add your message definitions here
// Example (Requests must always start with Metadata):
// message YourRequest {
// Metadata metadata = 1;
// string stringField = 2;
// int32 int32Field = 3;
// }
`
// Write the template proto file
const protoFilePath = path.join(SCRIPT_DIR, `${serviceName}.proto`)
await fs.writeFile(protoFilePath, protoContent)
console.log(chalk.green(`Created template proto file at ${protoFilePath}`))
}
}
}
// Run the main function
main().catch((error) => {
console.error(chalk.red("Error:"), error)
+9
View File
@@ -19,6 +19,11 @@ message StringRequest {
string value = 2;
}
message StringArrayRequest {
Metadata metadata = 1;
repeated string value = 2;
}
message String {
string value = 1;
}
@@ -49,3 +54,7 @@ message BooleanRequest {
message Boolean {
bool value = 1;
}
message StringArray {
repeated string values = 1;
}
+38 -1
View File
@@ -22,6 +22,44 @@ service FileService {
// Search git commits in the workspace
rpc searchCommits(StringRequest) returns (GitCommits);
// Convert URIs to workspace-relative paths
rpc getRelativePaths(RelativePathsRequest) returns (RelativePaths);
// Search for files in the workspace with fuzzy matching
rpc searchFiles(FileSearchRequest) returns (FileSearchResults);
}
// Request to convert a list of URIs to relative paths
message RelativePathsRequest {
Metadata metadata = 1;
repeated string uris = 2;
}
// Response containing the converted relative paths
message RelativePaths {
repeated string paths = 1;
}
// Request for file search operations
message FileSearchRequest {
Metadata metadata = 1;
string query = 2; // Search query string
optional string mentions_request_id = 3; // Optional request ID for tracking requests
optional int32 limit = 4; // Optional limit for results (default: 20)
}
// Result for file search operations
message FileSearchResults {
repeated FileInfo results = 1; // Array of file/folder results
optional string mentions_request_id = 2; // Echo of the request ID for tracking
}
// File information structure for search results
message FileInfo {
string path = 1; // Relative path from workspace root
string type = 2; // "file" or "folder"
optional string label = 3; // Display name (usually basename)
}
// Response for searchCommits
@@ -52,4 +90,3 @@ message RuleFile {
string display_name = 2; // Filename for display purposes
bool already_exists = 3; // For createRuleFile, indicates if file already existed
}
+30
View File
@@ -0,0 +1,30 @@
syntax = "proto3";
package cline;
option java_package = "bot.cline.proto";
option java_multiple_files = true;
import "common.proto";
// Service for model-related operations
service ModelsService {
// Fetches available models from Ollama
rpc getOllamaModels(StringRequest) returns (StringArray);
// Fetches available models from LM Studio
rpc getLmStudioModels(StringRequest) returns (StringArray);
// Fetches available models from VS Code LM API
rpc getVsCodeLmModels(EmptyRequest) returns (VsCodeLmModelsArray);
}
// List of VS Code LM models
message VsCodeLmModelsArray {
repeated VsCodeLmModel models = 1;
}
// Structure representing a VS Code LM model
message VsCodeLmModel {
string vendor = 1;
string family = 2;
string version = 3;
string id = 4;
}
+13
View File
@@ -0,0 +1,13 @@
syntax = "proto3";
package cline;
import "common.proto";
service StateService {
rpc getLatestState(EmptyRequest) returns (State);
rpc subscribeToState(EmptyRequest) returns (stream State);
}
message State {
string state_json = 1;
}
+67
View File
@@ -11,8 +11,20 @@ service TaskService {
rpc cancelTask(EmptyRequest) returns (Empty);
// Clears the current task
rpc clearTask(EmptyRequest) returns (Empty);
// Deletes multiple tasks with the given IDs
rpc deleteTasksWithIds(StringArrayRequest) returns (Empty);
// Creates a new task with the given text and optional images
rpc newTask(NewTaskRequest) returns (Empty);
// Shows a task with the specified ID
rpc showTaskWithId(StringRequest) returns (TaskResponse);
// Exports a task with the given ID to markdown
rpc exportTaskWithId(StringRequest) returns (Empty);
// Toggles the favorite status of a task
rpc toggleTaskFavorite(TaskFavoriteRequest) returns (Empty);
// Deletes all non-favorited tasks
rpc deleteNonFavoritedTasks(EmptyRequest) returns (DeleteNonFavoritedTasksResults);
// Gets filtered task history
rpc getTaskHistory(GetTaskHistoryRequest) returns (TaskHistoryArray);
}
// Request message for creating a new task
@@ -21,3 +33,58 @@ message NewTaskRequest {
string text = 2;
repeated string images = 3;
}
// Request message for toggling task favorite status
message TaskFavoriteRequest {
Metadata metadata = 1;
string task_id = 2;
bool is_favorited = 3;
}
// Response for task details
message TaskResponse {
string id = 1;
string task = 2;
int64 ts = 3;
bool is_favorited = 4;
int64 size = 5;
double total_cost = 6;
int32 tokens_in = 7;
int32 tokens_out = 8;
int32 cache_writes = 9;
int32 cache_reads = 10;
}
// Results returned when deleting non-favorited tasks
message DeleteNonFavoritedTasksResults {
int32 tasks_preserved = 1;
int32 tasks_deleted = 2;
}
// Request for getting task history with filtering
message GetTaskHistoryRequest {
Metadata metadata = 1;
bool favorites_only = 2;
string search_query = 3;
string sort_by = 4;
}
// Response for task history
message TaskHistoryArray {
repeated TaskItem tasks = 1;
int32 total_count = 2;
}
// Task item details for history list
message TaskItem {
string id = 1;
string task = 2;
int64 ts = 3;
bool is_favorited = 4;
int64 size = 5;
double total_cost = 6;
int32 tokens_in = 7;
int32 tokens_out = 8;
int32 cache_writes = 9;
int32 cache_reads = 10;
}
+1 -1
View File
@@ -6,7 +6,7 @@ option java_multiple_files = true;
import "common.proto";
service WebContentService {
service WebService {
rpc checkIsImageUrl(StringRequest) returns (IsImageUrl);
}
+137
View File
@@ -0,0 +1,137 @@
const { execSync } = require("child_process")
const readline = require("readline")
const os = require("os")
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
const ask = (question) => new Promise((resolve) => rl.question(`\n${question}`, resolve))
const getClineVersion = () => {
try {
const extensions = execSync("code --list-extensions --show-versions").toString()
const clineMatch = extensions.match(/claude-dev@(\d+\.\d+\.\d+)/)
return clineMatch ? clineMatch[1] : "Not installed"
} catch (err) {
return "Error getting version"
}
}
const collectSystemInfo = () => {
let cpuInfo = "N/A"
let memoryInfo = "N/A"
try {
if (process.platform === "darwin") {
cpuInfo = execSync("sysctl -n machdep.cpu.brand_string").toString().trim()
memoryInfo = execSync("sysctl -n hw.memsize").toString().trim()
memoryInfo = `${Math.round(parseInt(memoryInfo) / 1e9)} GB RAM`
} else {
// Linux specific commands
cpuInfo = execSync("lscpu").toString().split("\n").slice(0, 5).join("\n")
memoryInfo = execSync("free -h").toString()
}
} catch (err) {
// Fallback for unsupported systems
cpuInfo = Array.from(new Set(os.cpus().map((c) => c.model))).join("\n")
memoryInfo = `${Math.round(os.totalmem() / 1e9)} GB RAM`
}
return {
cpuInfo,
memoryInfo,
os: `${os.arch()}; ${os.version()}`,
nodeVersion: execSync("node -v").toString().trim(),
npmVersion: execSync("npm -v").toString().trim(),
clineVersion: getClineVersion(),
}
}
const checkGitHubAuth = async () => {
try {
execSync("gh auth status", { stdio: "ignore" })
return true
} catch (err) {
console.log("\nGitHub authentication required.")
console.log("\nPlease run the following command in your terminal to authenticate:")
console.log("\n gh auth login\n")
console.log("After authenticating, run this script again.")
return false
}
}
const createIssueUrl = (systemInfo, issueTitle) => {
return (
`https://github.com/cline/cline/issues/new?template=bug_report.yml` +
`&title=${issueTitle}` +
`&operating-system=${systemInfo.os}` +
`&cline-version=${systemInfo.clineVersion}` +
`&system-info=${
`Node: ${systemInfo.nodeVersion}\n` +
`npm: ${systemInfo.npmVersion}\n` +
`CPU Info: ${systemInfo.cpuInfo}\n` +
`Free RAM: ${systemInfo.memoryInfo}`
}`
)
}
const openUrl = (url) => {
try {
switch (process.platform) {
case "darwin":
execSync(`open "${url}"`)
break
case "win32":
execSync(`start "" "${url}"`)
break
case "linux":
execSync(`xdg-open "${url}"`)
break
default:
console.log("\nPlease open this URL in your browser:")
console.log(url)
}
} catch (err) {
console.log("\nFailed to open URL automatically. Please open this URL in your browser:")
console.log(url)
}
}
const submitIssue = async (issueTitle, systemInfo) => {
try {
const issueUrl = createIssueUrl(systemInfo, issueTitle)
console.log("\nOpening GitHub issue creation page in your browser...")
openUrl(issueUrl)
} catch (err) {
console.error("\nFailed to create issue URL:", err.message)
}
}
async function main() {
const consent = await ask("Do you consent to collect system data and submit a GitHub issue? (y/n): ")
if (consent.trim().toLowerCase() !== "y") {
console.log("\nAborted.")
rl.close()
return
}
console.log("Collecting system data...")
const systemInfo = collectSystemInfo()
const isAuthenticated = await checkGitHubAuth()
if (!isAuthenticated) {
rl.close()
return
}
const issueTitle = await ask("Enter the title for your issue: ")
await submitIssue(issueTitle, systemInfo)
rl.close()
}
main().catch((err) => {
console.error("\nAn error occurred:", err)
rl.close()
})
+19 -6
View File
@@ -58,6 +58,10 @@ export class AwsBedrockHandler implements ApiHandler {
// initialization, and allowing for session renewal if necessary as well
const client = await this.getAnthropicClient()
// AWS SDK prioritizes AWS_PROFILE over AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair
// If this is set as an env variable already (ie. from ~/.zshrc) it will override credentials configured by Cline
const previousEnv = process.env
delete process.env["AWS_PROFILE"]
const stream = await client.messages.create({
model: modelId,
max_tokens: model.info.maxTokens || 8192,
@@ -103,6 +107,7 @@ export class AwsBedrockHandler implements ApiHandler {
}),
stream: true,
})
process.env = previousEnv
for await (const chunk of stream) {
switch (chunk.type) {
@@ -213,10 +218,14 @@ export class AwsBedrockHandler implements ApiHandler {
return await AwsBedrockHandler.withTempEnv(
() => {
AwsBedrockHandler.setEnv("AWS_REGION", this.options.awsRegion)
AwsBedrockHandler.setEnv("AWS_ACCESS_KEY_ID", this.options.awsAccessKey)
AwsBedrockHandler.setEnv("AWS_SECRET_ACCESS_KEY", this.options.awsSecretKey)
AwsBedrockHandler.setEnv("AWS_SESSION_TOKEN", this.options.awsSessionToken)
AwsBedrockHandler.setEnv("AWS_PROFILE", this.options.awsProfile)
if (this.options.awsUseProfile) {
AwsBedrockHandler.setEnv("AWS_PROFILE", this.options.awsProfile)
} else {
delete process.env["AWS_PROFILE"]
AwsBedrockHandler.setEnv("AWS_ACCESS_KEY_ID", this.options.awsAccessKey)
AwsBedrockHandler.setEnv("AWS_SECRET_ACCESS_KEY", this.options.awsSecretKey)
AwsBedrockHandler.setEnv("AWS_SESSION_TOKEN", this.options.awsSessionToken)
}
},
() => providerChain(),
)
@@ -263,10 +272,14 @@ export class AwsBedrockHandler implements ApiHandler {
}
/**
* Gets the appropriate model ID, accounting for cross-region inference if enabled
* Gets the appropriate model ID, accounting for cross-region inference if enabled.
* If the model ID is an ARN that contains a slash, you will get the URL encoded ARN.
*/
async getModelId(): Promise<string> {
if (this.options.awsUseCrossRegionInference) {
if (this.options.awsBedrockCustomSelected && this.getModel().id.includes("/")) {
return encodeURIComponent(this.getModel().id)
}
if (!this.options.awsBedrockCustomSelected && this.options.awsUseCrossRegionInference) {
const regionPrefix = this.getRegion().slice(0, 3)
switch (regionPrefix) {
case "us-":
+1 -2
View File
@@ -107,9 +107,8 @@ export class ClineHandler implements ApiHandler {
const generation = response.data
return {
type: "usage",
// at this time there's no support for gatting cached_tokens from generation endpoint
cacheWriteTokens: 0,
cacheReadTokens: 0,
cacheReadTokens: generation?.native_tokens_cached || 0,
inputTokens: generation?.native_tokens_prompt || 0,
outputTokens: generation?.native_tokens_completion || 0,
totalCost: generation?.total_cost || 0,
+6 -308
View File
@@ -1,7 +1,6 @@
import type { Anthropic } from "@anthropic-ai/sdk"
// Restore GenerateContentConfig import and add GenerateContentResponseUsageMetadata
import { GoogleGenAI, type Content, type GenerateContentConfig, type GenerateContentResponseUsageMetadata } from "@google/genai"
import NodeCache from "node-cache"
import { withRetry } from "../retry"
import { ApiHandler } from "../"
import { ApiHandlerOptions, geminiDefaultModelId, GeminiModelId, geminiModels, ModelInfo } from "@shared/api"
@@ -39,12 +38,6 @@ export class GeminiHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: GoogleGenAI
// Enhanced caching system
private contentCaches: NodeCache // Stores cache details (key, count, etc.)
private isCacheBusy = false
private taskCacheNames: Map<string, string> = new Map() // Maps taskId to cache name for stable lookup
private taskCacheTokens: Map<string, number> = new Map() // Maps taskId to total tokens in cache
constructor(options: GeminiHandlerOptions) {
// Store the options
this.options = options
@@ -67,26 +60,13 @@ export class GeminiHandler implements ApiHandler {
this.client = new GoogleGenAI({ apiKey: options.geminiApiKey })
}
// Initialize cache with TTL and check period
this.contentCaches = new NodeCache({
stdTTL: DEFAULT_CACHE_TTL_SECONDS,
checkperiod: DEFAULT_CACHE_TTL_SECONDS,
})
}
/**
* Creates a message using the Gemini API with optimized caching and split cost accounting.
*
* This method implements a task-based caching strategy:
* 1. Each task gets its own cache, identified by taskId
* 2. On first call for a task, a new cache is created
* 3. On subsequent calls, the existing cache is reused and only new messages are sent
* 4. Cache operations are tracked for accurate cost accounting
* Creates a message using the Gemini API with implicit caching.
*
* Cost accounting:
* - Immediate costs (returned in the usage object): Input tokens, output tokens, cache read costs
* - Ongoing costs (tracked at task level): Cache storage costs for the TTL period
*
* @param systemPrompt The system prompt to use for the message
* @param messages The conversation history to include in the message
@@ -97,54 +77,6 @@ export class GeminiHandler implements ApiHandler {
const { id: model, info } = this.getModel()
const contents = messages.map(convertAnthropicMessageToGemini)
// Ensure we have a stable cache key (taskId)
if (!this.options.taskId) {
console.warn("[GeminiHandler] No taskId provided, caching will be disabled")
}
const taskId = this.options.taskId
// Calculate total content length for cache eligibility check
const contentsLength = systemPrompt.length + this.getMessagesLength(contents)
// Minimum token threshold for caching (approx 4096 tokens)
const CONTEXT_CACHE_TOKEN_MINIMUM = 4096
let uncachedContent: Content[] | undefined = undefined
let cachedContent: string | undefined = undefined
// Check if caching is available and content is large enough to benefit from caching
// We only enable caching for conversations above a certain size to avoid overhead for small requests
const isCacheAvailable = info.supportsPromptCache && contentsLength > 4 * CONTEXT_CACHE_TOKEN_MINIMUM && taskId
// This flag tracks whether this operation involves a cache write/update
// It's used to track task-level ongoing costs, not immediate costs
let cacheWrite = false
if (isCacheAvailable) {
// Check if we already have a cache for this task
const existingCacheName = this.taskCacheNames.get(taskId)
const cacheEntry = existingCacheName ? this.contentCaches.get<{ key: string; count: number }>(taskId) : undefined
if (cacheEntry) {
// Use existing cache
uncachedContent = contents.slice(cacheEntry.count, contents.length)
cachedContent = cacheEntry.key
console.log(
`[GeminiHandler] using existing cache for task ${taskId}: ${cacheEntry.count} cached messages (${cacheEntry.key}) and ${uncachedContent.length} uncached messages`,
)
}
// Create or update cache only if there's new content to add
const shouldUpdateCache = !existingCacheName || (cacheEntry && uncachedContent && uncachedContent.length > 0)
if (shouldUpdateCache) {
// If we should update the cache, then there will be a cache write
cacheWrite = true
}
}
const isCacheUsed = !!cachedContent
// Configure thinking budget if supported
const thinkingBudget = this.options.thinkingBudgetTokens ?? 0
const maxBudget = info.thinkingConfig?.maxBudget ?? 0
@@ -153,10 +85,7 @@ export class GeminiHandler implements ApiHandler {
const requestConfig: GenerateContentConfig = {
// Add base URL if configured
httpOptions: this.options.geminiBaseUrl ? { baseUrl: this.options.geminiBaseUrl } : undefined,
// Only include systemInstruction if NOT using the cache
...(isCacheUsed ? {} : { systemInstruction: systemPrompt }),
...{ systemInstruction: systemPrompt },
// Set temperature (default to 0)
temperature: 0,
}
@@ -171,19 +100,12 @@ export class GeminiHandler implements ApiHandler {
// Generate content using the configured parameters
const result = await this.client.models.generateContentStream({
model,
contents: uncachedContent ?? contents,
contents: contents,
config: {
...requestConfig,
...(isCacheUsed ? { cachedContent } : {}),
},
})
// Update the cache after the LLM request is already sent to avoid blocking
// We only update the cache if we have a taskId and the cache write flag is set
// This is a non-blocking operation and will not affect the response time
if (cacheWrite && taskId) {
this.updateCacheContent(taskId, model, contents, systemPrompt)
}
// Track usage metadata
let lastUsageMetadata: GenerateContentResponseUsageMetadata | undefined
@@ -207,7 +129,7 @@ export class GeminiHandler implements ApiHandler {
const outputTokens = lastUsageMetadata.candidatesTokenCount ?? 0
const cacheReadTokens = lastUsageMetadata.cachedContentTokenCount
// Calculate immediate costs only (excluding cache write/storage costs)
// Calculate immediate costs
const totalCost = this.calculateCost({
info,
inputTokens,
@@ -215,214 +137,17 @@ export class GeminiHandler implements ApiHandler {
cacheReadTokens,
})
// Store the token count for task-level ongoing cost tracking
// This is not included in the immediate costs returned to the user
const cacheWriteTokens = cacheWrite ? inputTokens : undefined
// If this is a cache write operation, update the task's ongoing costs
if (cacheWrite && this.options.taskId && inputTokens > 0) {
// Log the ongoing costs for debugging
const ongoingCosts = this.getTaskOngoingCosts(this.options.taskId)
console.log(
`[GeminiHandler] Task ${this.options.taskId} ongoing costs: $${ongoingCosts?.toFixed(6) ?? "unknown"}`,
)
}
yield {
type: "usage",
inputTokens,
outputTokens,
cacheReadTokens,
cacheWriteTokens,
cacheWriteTokens: 0,
totalCost,
}
}
}
/**
* Lists all caches for the current API key.
*
* According to the Gemini API documentation, you can retrieve metadata for all uploaded caches
* using the caches.list() method. This is useful for monitoring cache usage and cleanup.
*
* @param pageSize Optional number of caches to return per page (default: 10)
* @returns A promise that resolves to an array of cache metadata objects
*/
public async listCaches(pageSize: number = 10): Promise<any[]> {
try {
const caches: any[] = []
const pager = await this.client.caches.list({ config: { pageSize } })
let page = pager.page
while (true) {
for (const cache of page) {
caches.push(cache)
}
if (!pager.hasNextPage()) {
break
}
page = await pager.nextPage()
}
return caches
} catch (error) {
console.error(`[GeminiHandler] Failed to list caches:`, error)
return []
}
}
/**
* Updates the content of a cache for a specific task.
*
* Since the Gemini API doesn't support incremental updates to cache content,
* this method:
* 1. Creates a new cache with the full content (old + new)
* 2. Deletes the old cache if it exists
* 3. Updates our local tracking to point to the new cache
*
* @param taskId The ID of the task whose cache should be updated
* @param model The model to use for the cache
* @param contents The full content to cache (including both old and new messages)
* @param systemInstruction The system instruction to include in the cache
*/
private async updateCacheContent(
taskId: string,
model: string,
contents: Content[],
systemInstruction: string,
): Promise<void> {
if (this.isCacheBusy) {
console.log(`[GeminiHandler] Cache is busy, skipping update for task ${taskId}`)
return
}
this.isCacheBusy = true
const timestamp = Date.now()
const existingCacheName = this.taskCacheNames.get(taskId)
try {
// 1. Create a new cache with the full content
const result = await this.client.caches.create({
model,
config: {
contents,
systemInstruction,
ttl: `${DEFAULT_CACHE_TTL_SECONDS}s`,
httpOptions: { timeout: 120_000 },
},
})
const { name, usageMetadata } = result
if (name) {
// 2. Delete the old cache if it exists (non-blocking)
// We don't await this operation to avoid blocking the main flow if deletion fails
if (existingCacheName) {
// Schedule cache deletion in the background
setTimeout(() => {
this.client.caches
.delete({ name: existingCacheName })
.then(() => {
console.log(`[GeminiHandler] Deleted old cache ${existingCacheName} for task ${taskId}`)
})
.catch((error) => {
console.error(`[GeminiHandler] Failed to delete old cache ${existingCacheName}:`, error)
console.log(`[GeminiHandler] Continuing without deleting old cache. It will expire after TTL.`)
})
}, 1000)
}
// 3. Update our local tracking
this.contentCaches.set<{ key: string; count: number }>(taskId, {
key: name,
count: contents.length,
})
this.taskCacheNames.set(taskId, name)
// Track total tokens in cache for ongoing cost calculation
const totalTokens = usageMetadata?.totalTokenCount ?? 0
this.taskCacheTokens.set(taskId, totalTokens)
const operation = existingCacheName ? "Updated" : "Created new"
console.log(
`[GeminiHandler] ${operation} cache for task ${taskId}: ${contents.length} messages (${totalTokens} tokens) in ${Date.now() - timestamp}ms`,
)
return // Indicate that a cache write occurred
}
return
} catch (error) {
console.error(`[GeminiHandler] Failed to update cache for task ${taskId}:`, error)
return
} finally {
this.isCacheBusy = false
}
}
/**
* Updates the TTL of an existing cache.
*
* According to the Gemini API documentation, you can update the TTL of a cache
* using the caches.update() method. This is useful for extending the lifetime
* of a cache that's still being used.
*
* @param taskId The ID of the task whose cache TTL should be updated
* @param ttlSeconds The new TTL in seconds
* @returns A promise that resolves to the updated cache, or undefined if the update fails
*/
public async updateCacheTTL(taskId: string, ttlSeconds: number = DEFAULT_CACHE_TTL_SECONDS): Promise<any> {
const cacheName = this.taskCacheNames.get(taskId)
if (!cacheName) {
console.warn(`[GeminiHandler] No cache found for task ${taskId}, cannot update TTL`)
return
}
try {
const updatedCache = await this.client.caches.update({
name: cacheName,
config: { ttl: `${ttlSeconds}s` },
})
console.log(`[GeminiHandler] Updated TTL for cache ${cacheName} to ${ttlSeconds}s`)
return updatedCache
} catch (error) {
console.error(`[GeminiHandler] Failed to update TTL for cache ${cacheName}:`, error)
}
}
/**
* Calculate the ongoing costs for a task based on cache storage.
*
* This method calculates the cost of holding tokens in cache for the TTL period.
* These costs are separate from the immediate costs of API calls and should be
* tracked at the task level rather than the message level.
*
* TODO: Surface these ongoing costs to the user in the UI, possibly in:
* - The task header/summary
* - A dedicated "costs" panel or tooltip
* - As part of the total cost calculation for the task
*
* @param taskId The ID of the task to calculate ongoing costs for
* @returns The ongoing cost in dollars, or undefined if no cache exists for the task
*/
public getTaskOngoingCosts(taskId: string): number | undefined {
const tokens = this.taskCacheTokens.get(taskId)
if (!tokens) {
return undefined
}
const { info } = this.getModel()
if (!info.cacheWritesPrice) {
return undefined
}
// Calculate the cost of holding tokens in cache for the TTL period
// (tokens / 1M) * (price per 1M tokens) * (cache TTL in hours)
return info.cacheWritesPrice * (tokens / 1_000_000) * (DEFAULT_CACHE_TTL_SECONDS / 3600)
}
/**
* Calculate the immediate dollar cost of the API call based on token usage and model pricing.
*
@@ -430,21 +155,18 @@ export class GeminiHandler implements ApiHandler {
* - Input token costs (for uncached tokens)
* - Output token costs
* - Cache read costs
* - Gemini implicit caching has no write costs
*
* It does NOT include ongoing costs like cache storage, which are tracked separately
* at the task level through getTaskOngoingCosts().
*/
public calculateCost({
info,
inputTokens,
outputTokens,
cacheWriteTokens = 0,
cacheReadTokens = 0,
}: {
info: ModelInfo
inputTokens: number
outputTokens: number
cacheWriteTokens?: number
cacheReadTokens?: number
}) {
// Exit early if any required pricing information is missing
@@ -454,9 +176,7 @@ export class GeminiHandler implements ApiHandler {
let inputPrice = info.inputPrice
let outputPrice = info.outputPrice
let cacheWritesPrice = info.cacheWritesPrice ?? 0
// Right now, we only show the immediate costs of caching and not the ongoing costs of storing the cache
cacheWritesPrice = 0
let cacheReadsPrice = info.cacheReadsPrice ?? 0
// If there's tiered pricing then adjust prices based on the input tokens used
@@ -465,7 +185,6 @@ export class GeminiHandler implements ApiHandler {
if (tier) {
inputPrice = tier.inputPrice ?? inputPrice
outputPrice = tier.outputPrice ?? outputPrice
cacheWritesPrice = tier.cacheWritesPrice ?? cacheWritesPrice
cacheReadsPrice = tier.cacheReadsPrice ?? cacheReadsPrice
}
}
@@ -502,27 +221,6 @@ export class GeminiHandler implements ApiHandler {
return totalCost
}
/**
* Calculate the total length of all messages for cache eligibility check
*/
private getMessagesLength(contents: Content[]): number {
return contents.reduce((total, content) => {
if (!content.parts) {
return total
}
return (
total +
content.parts.reduce((partTotal, part) => {
if (typeof part.text === "string") {
return partTotal + part.text.length
}
return partTotal
}, 0)
)
}, 0)
}
/**
* Get the model ID and info for the current configuration
*/
+1 -1
View File
@@ -58,7 +58,7 @@ export class LiteLlmHandler implements ApiHandler {
content: systemPrompt,
}
const modelId = this.options.liteLlmModelId || liteLlmDefaultModelId
const isOminiModel = modelId.includes("o1-mini") || modelId.includes("o3-mini")
const isOminiModel = modelId.includes("o1-mini") || modelId.includes("o3-mini") || modelId.includes("o4-mini")
// Configuration for extended thinking
const budgetTokens = this.options.thinkingBudgetTokens || 0
+2 -1
View File
@@ -18,7 +18,8 @@ export class OpenAiHandler implements ApiHandler {
// Use azureApiVersion to determine if this is an Azure endpoint, since the URL may not always contain 'azure.com'
if (
this.options.azureApiVersion ||
(this.options.openAiBaseUrl?.toLowerCase().includes("azure.com") &&
((this.options.openAiBaseUrl?.toLowerCase().includes("azure.com") ||
this.options.openAiBaseUrl?.toLowerCase().includes("azure.us")) &&
!this.options.openAiModelId?.toLowerCase().includes("deepseek"))
) {
this.client = new AzureOpenAI({
+1 -2
View File
@@ -105,9 +105,8 @@ export class OpenRouterHandler implements ApiHandler {
// console.log("OpenRouter generation details:", generation)
return {
type: "usage",
// at this time there's no support for gatting cached_tokens from generation endpoint
cacheWriteTokens: 0,
cacheReadTokens: 0,
cacheReadTokens: generation?.native_tokens_cached || 0,
// openrouter generation endpoint fails often
inputTokens: generation?.native_tokens_prompt || 0,
outputTokens: generation?.native_tokens_completion || 0,
+1 -1
View File
@@ -34,7 +34,7 @@ export class RequestyHandler implements ApiHandler {
const reasoningEffort = this.options.o3MiniReasoningEffort || "medium"
const reasoning = { reasoning_effort: reasoningEffort }
const reasoningArgs = model.id === "openai/o3-mini" ? reasoning : {}
const reasoningArgs = model.id.startsWith("openai/o") ? reasoning : {}
const thinkingBudget = this.options.thinkingBudgetTokens || 0
const thinking =
+70 -48
View File
@@ -21,7 +21,7 @@ export async function createOpenRouterStream(
// prompt caching: https://openrouter.ai/docs/prompt-caching
// this was initially specifically for claude models (some models may 'support prompt caching' automatically without this)
// includes custom support for gemini which does not have iterative caching
// handles direct model.id match logic
switch (model.id) {
case "anthropic/claude-3.7-sonnet":
case "anthropic/claude-3.7-sonnet:beta":
@@ -71,56 +71,78 @@ export async function createOpenRouterStream(
}
})
break
case "google/gemini-2.5-pro-preview-03-25":
case "google/gemini-2.0-flash-001":
case "google/gemini-flash-1.5":
case "google/gemini-pro-1.5":
// gemini only uses the last breakpoint for caching, so the others will be ignored
openAiMessages[0] = {
role: "system",
content: [
{
type: "text",
text: systemPrompt,
// @ts-ignore-next-line
cache_control: { type: "ephemeral" },
},
],
}
const GEMINI_CACHE_USER_MESSAGE_INTERVAL = 4 // add new breakpoint every 4 turns
const userMessages = openAiMessages.filter((msg) => msg.role === "user")
const userMessageCount = userMessages.length
const targetUserMessageNumber =
Math.floor(userMessageCount / GEMINI_CACHE_USER_MESSAGE_INTERVAL) * GEMINI_CACHE_USER_MESSAGE_INTERVAL
if (targetUserMessageNumber > 0) {
// otherwise dont need to add a breakpoint
const msg = userMessages[targetUserMessageNumber - 1]
if (msg) {
if (typeof msg.content === "string") {
msg.content = [{ type: "text", text: msg.content }]
}
if (Array.isArray(msg.content)) {
// NOTE: this is fine since env details will always be added at the end. but if it weren't there, and the user added a image_url type message, it would pop a text part before it and then move it after to the end.
let lastTextPart = msg.content.filter((part) => part.type === "text").pop()
if (!lastTextPart) {
lastTextPart = { type: "text", text: "..." }
msg.content.push(lastTextPart)
}
// @ts-ignore-next-line
lastTextPart["cache_control"] = { type: "ephemeral" }
}
}
}
break
default:
break
}
// handles gemini caching logic
if (model.id.startsWith("google/") && model.info.supportsPromptCache) {
// gemini only uses the last breakpoint for caching, so the others will be ignored
openAiMessages[0] = {
role: "system",
content: [
{
type: "text",
text: systemPrompt,
// @ts-ignore-next-line
cache_control: { type: "ephemeral" },
},
],
}
// for safety, but this should always be the case
if (openAiMessages.length >= 2) {
const msg = openAiMessages[1]
if (msg) {
if (typeof msg.content === "string") {
msg.content = [{ type: "text", text: msg.content }]
}
if (Array.isArray(msg.content)) {
// NOTE: this is fine since env details will always be added at the end. but if it weren't there, and the user added a image_url type message, it would pop a text part before it and then move it after to the end.
let lastTextPart = msg.content.filter((part) => part.type === "text").pop()
if (!lastTextPart) {
lastTextPart = { type: "text", text: "..." }
msg.content.push(lastTextPart)
}
// @ts-ignore-next-line
lastTextPart["cache_control"] = { type: "ephemeral" }
}
}
}
// it doesn't make sense to alter breakpoints at all with the gemini cache implementation at this time
/*const GEMINI_CACHE_USER_MESSAGE_INTERVAL = 4 // add new breakpoint every 4 turns
const userMessages = openAiMessages.filter((msg) => msg.role === "user")
const userMessageCount = userMessages.length
const targetUserMessageNumber =
Math.floor(userMessageCount / GEMINI_CACHE_USER_MESSAGE_INTERVAL) * GEMINI_CACHE_USER_MESSAGE_INTERVAL
if (targetUserMessageNumber > 0) {
// otherwise dont need to add a breakpoint
const msg = userMessages[targetUserMessageNumber - 1]
if (msg) {
if (typeof msg.content === "string") {
msg.content = [{ type: "text", text: msg.content }]
}
if (Array.isArray(msg.content)) {
// NOTE: this is fine since env details will always be added at the end. but if it weren't there, and the user added a image_url type message, it would pop a text part before it and then move it after to the end.
let lastTextPart = msg.content.filter((part) => part.type === "text").pop()
if (!lastTextPart) {
lastTextPart = { type: "text", text: "..." }
msg.content.push(lastTextPart)
}
// @ts-ignore-next-line
lastTextPart["cache_control"] = { type: "ephemeral" }
}
}
}*/
}
// Not sure how openrouter defaults max tokens when no value is provided, but the anthropic api requires this value and since they offer both 4096 and 8192 variants, we should ensure 8192.
// (models usually default to max tokens allowed)
let maxTokens: number | undefined
@@ -190,7 +212,7 @@ export async function createOpenRouterStream(
stream_options: { include_usage: true },
transforms: shouldApplyMiddleOutTransform ? ["middle-out"] : undefined,
include_reasoning: true,
...(model.id === "openai/o3-mini" ? { reasoning_effort: o3MiniReasoningEffort || "medium" } : {}),
...(model.id.startsWith("openai/o") ? { reasoning_effort: o3MiniReasoningEffort || "medium" } : {}),
...(reasoning ? { reasoning } : {}),
...(openRouterProviderSorting ? { provider: { sort: openRouterProviderSorting } } : {}),
})

Some files were not shown because too many files have changed in this diff Show More