-
Notifications
You must be signed in to change notification settings - Fork 0
feat: native PHP MCP server via laravel/mcp #134
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+2,619
−123
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace App\Mcp\Servers; | ||
|
|
||
| use App\Mcp\Tools\ContextTool; | ||
| use App\Mcp\Tools\CorrectTool; | ||
| use App\Mcp\Tools\RecallTool; | ||
| use App\Mcp\Tools\RememberTool; | ||
| use App\Mcp\Tools\StatsTool; | ||
| use Laravel\Mcp\Server; | ||
| use Laravel\Mcp\Server\Attributes\Instructions; | ||
| use Laravel\Mcp\Server\Attributes\Name; | ||
| use Laravel\Mcp\Server\Attributes\Version; | ||
|
|
||
| #[Name('Knowledge')] | ||
| #[Version('1.0.0')] | ||
| #[Instructions('Semantic knowledge base with vector search. Use `recall` to search, `remember` to capture discoveries, `correct` to fix wrong knowledge, `context` to load project-relevant entries, and `stats` for health checks. All tools auto-detect the current project from git context.')] | ||
| class KnowledgeServer extends Server | ||
| { | ||
| protected array $tools = [ | ||
| RecallTool::class, | ||
| RememberTool::class, | ||
| CorrectTool::class, | ||
| ContextTool::class, | ||
| StatsTool::class, | ||
| ]; | ||
|
|
||
| protected array $resources = []; | ||
|
|
||
| protected array $prompts = []; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,244 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace App\Mcp\Tools; | ||
|
|
||
| use App\Services\EntryMetadataService; | ||
| use App\Services\ProjectDetectorService; | ||
| use App\Services\QdrantService; | ||
| use Illuminate\Contracts\JsonSchema\JsonSchema; | ||
| use Laravel\Mcp\Request; | ||
| use Laravel\Mcp\Response; | ||
| use Laravel\Mcp\Server\Attributes\Description; | ||
| use Laravel\Mcp\Server\Tool; | ||
| use Laravel\Mcp\Server\Tools\Annotations\IsIdempotent; | ||
| use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly; | ||
|
|
||
| #[Description('Load project-relevant knowledge context. Returns entries grouped by category, ranked by usage and recency. Use at session start for deep project context.')] | ||
| #[IsReadOnly] | ||
| #[IsIdempotent] | ||
| class ContextTool extends Tool | ||
| { | ||
| private const CHARS_PER_TOKEN = 4; | ||
|
|
||
| private const CATEGORY_ORDER = [ | ||
| 'architecture', | ||
| 'patterns', | ||
| 'decisions', | ||
| 'gotchas', | ||
| 'debugging', | ||
| 'testing', | ||
| 'deployment', | ||
| 'security', | ||
| ]; | ||
|
|
||
| public function __construct( | ||
| private readonly QdrantService $qdrant, | ||
| private readonly EntryMetadataService $metadata, | ||
| private readonly ProjectDetectorService $projectDetector, | ||
| ) {} | ||
|
|
||
| public function handle(Request $request): Response | ||
| { | ||
| $project = is_string($request->get('project')) ? $request->get('project') : $this->projectDetector->detect(); | ||
|
|
||
| /** @var array<string>|null $categories */ | ||
| $categories = is_array($request->get('categories')) ? $request->get('categories') : null; | ||
| $maxTokens = is_int($request->get('max_tokens')) ? min($request->get('max_tokens'), 16000) : 4000; | ||
| $limit = is_int($request->get('limit')) ? min($request->get('limit'), 100) : 50; | ||
|
|
||
| $entries = $this->fetchEntries($categories, $limit, $project); | ||
|
|
||
| if ($entries === []) { | ||
| $available = $this->qdrant->listCollections(); | ||
| $projects = array_map( | ||
| fn (string $c): string => str_replace('knowledge_', '', $c), | ||
| $available | ||
| ); | ||
|
|
||
| return Response::text(json_encode([ | ||
| 'project' => $project, | ||
| 'entries' => [], | ||
| 'total' => 0, | ||
| 'message' => "No knowledge entries found for project '{$project}'.", | ||
| 'available_projects' => array_values($projects), | ||
| ], JSON_THROW_ON_ERROR)); | ||
| } | ||
|
|
||
| $ranked = $this->rankEntries($entries); | ||
| $grouped = $this->groupByCategory($ranked); | ||
| $truncated = $this->truncateToTokenBudget($grouped, $maxTokens); | ||
|
|
||
| $totalEntries = array_sum(array_map('count', $truncated)); | ||
|
|
||
| return Response::text(json_encode([ | ||
| 'project' => $project, | ||
| 'categories' => $truncated, | ||
| 'total' => $totalEntries, | ||
| 'available' => count($entries), | ||
| ], JSON_THROW_ON_ERROR)); | ||
| } | ||
|
|
||
| public function schema(JsonSchema $schema): array | ||
| { | ||
| return [ | ||
| 'project' => $schema->string() | ||
| ->description('Project namespace. Auto-detected from git if omitted.'), | ||
| 'categories' => $schema->array() | ||
| ->description('Filter to specific categories (e.g., ["architecture", "debugging"]).'), | ||
| 'max_tokens' => $schema->integer() | ||
| ->description('Maximum approximate token budget for response (default 4000).') | ||
| ->default(4000), | ||
| 'limit' => $schema->integer() | ||
| ->description('Maximum entries to fetch (default 50).') | ||
| ->default(50), | ||
| ]; | ||
| } | ||
|
|
||
| /** | ||
| * @param array<string>|null $categories | ||
| * @return array<int, array<string, mixed>> | ||
| */ | ||
| private function fetchEntries(?array $categories, int $limit, string $project): array | ||
| { | ||
| if ($categories !== null && $categories !== []) { | ||
| $entries = []; | ||
| $perCategory = max(1, intdiv($limit, count($categories))); | ||
|
|
||
| foreach ($categories as $category) { | ||
| $results = $this->qdrant->scroll( | ||
| ['category' => $category], | ||
| $perCategory, | ||
| $project | ||
| ); | ||
|
|
||
| foreach ($results->all() as $entry) { | ||
| $entries[] = $entry; | ||
| } | ||
| } | ||
|
|
||
| return $entries; | ||
| } | ||
|
|
||
| return $this->qdrant->scroll([], $limit, $project)->all(); | ||
| } | ||
|
|
||
| /** | ||
| * @param array<int, array<string, mixed>> $entries | ||
| * @return array<int, array<string, mixed>> | ||
| */ | ||
| private function rankEntries(array $entries): array | ||
| { | ||
| $now = time(); | ||
|
|
||
| usort($entries, function (array $a, array $b) use ($now): int { | ||
| $scoreA = $this->entryScore($a, $now); | ||
| $scoreB = $this->entryScore($b, $now); | ||
|
|
||
| return $scoreB <=> $scoreA; | ||
| }); | ||
|
|
||
| return $entries; | ||
| } | ||
|
|
||
| /** | ||
| * @param array<string, mixed> $entry | ||
| */ | ||
| private function entryScore(array $entry, int $now): float | ||
| { | ||
| $usageCount = (int) ($entry['usage_count'] ?? 0); | ||
| $updatedAt = $entry['updated_at'] ?? ''; | ||
| $timestamp = is_string($updatedAt) && $updatedAt !== '' ? strtotime($updatedAt) : $now; | ||
|
|
||
| if ($timestamp === false) { | ||
| $timestamp = $now; | ||
| } | ||
|
|
||
| $daysAgo = max(1, (int) (($now - $timestamp) / 86400)); | ||
|
|
||
| return ($usageCount * 2.0) + (100.0 / $daysAgo); | ||
| } | ||
|
|
||
| /** | ||
| * @param array<int, array<string, mixed>> $entries | ||
| * @return array<string, array<int, array<string, mixed>>> | ||
| */ | ||
| private function groupByCategory(array $entries): array | ||
| { | ||
| $grouped = []; | ||
|
|
||
| foreach ($entries as $entry) { | ||
| $category = is_string($entry['category'] ?? null) && ($entry['category'] ?? '') !== '' | ||
| ? $entry['category'] | ||
| : 'uncategorized'; | ||
|
|
||
| $grouped[$category][] = $this->formatEntry($entry); | ||
| } | ||
|
|
||
| $ordered = []; | ||
|
|
||
| foreach (self::CATEGORY_ORDER as $cat) { | ||
| if (isset($grouped[$cat])) { | ||
| $ordered[$cat] = $grouped[$cat]; | ||
| unset($grouped[$cat]); | ||
| } | ||
| } | ||
|
|
||
| ksort($grouped); | ||
|
|
||
| return array_merge($ordered, $grouped); | ||
| } | ||
|
|
||
| /** | ||
| * @param array<string, array<int, array<string, mixed>>> $grouped | ||
| * @return array<string, array<int, array<string, mixed>>> | ||
| */ | ||
| private function truncateToTokenBudget(array $grouped, int $maxTokens): array | ||
| { | ||
| $maxChars = $maxTokens * self::CHARS_PER_TOKEN; | ||
| $charCount = 0; | ||
| $result = []; | ||
|
|
||
| foreach ($grouped as $category => $entries) { | ||
| $categoryEntries = []; | ||
|
|
||
| foreach ($entries as $entry) { | ||
| $entryJson = json_encode($entry, JSON_THROW_ON_ERROR); | ||
| $entryLen = strlen($entryJson); | ||
|
|
||
| if ($charCount + $entryLen > $maxChars) { | ||
| break 2; | ||
| } | ||
|
|
||
| $categoryEntries[] = $entry; | ||
| $charCount += $entryLen; | ||
| } | ||
|
|
||
| if ($categoryEntries !== []) { | ||
| $result[$category] = $categoryEntries; | ||
| } | ||
| } | ||
|
|
||
| return $result; | ||
| } | ||
|
|
||
| /** | ||
| * @param array<string, mixed> $entry | ||
| * @return array<string, mixed> | ||
| */ | ||
| private function formatEntry(array $entry): array | ||
| { | ||
| $effectiveConfidence = $this->metadata->calculateEffectiveConfidence($entry); | ||
|
|
||
| return [ | ||
| 'id' => $entry['id'], | ||
| 'title' => $entry['title'] ?? '', | ||
| 'content' => $entry['content'] ?? '', | ||
| 'confidence' => $effectiveConfidence, | ||
| 'freshness' => $this->metadata->isStale($entry) ? 'stale' : 'fresh', | ||
| 'priority' => $entry['priority'] ?? 'medium', | ||
| 'tags' => $entry['tags'] ?? [], | ||
| ]; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace App\Mcp\Tools; | ||
|
|
||
| use App\Services\CorrectionService; | ||
| use Illuminate\Contracts\JsonSchema\JsonSchema; | ||
| use Laravel\Mcp\Request; | ||
| use Laravel\Mcp\Response; | ||
| use Laravel\Mcp\Server\Attributes\Description; | ||
| use Laravel\Mcp\Server\Tool; | ||
|
|
||
| #[Description('Correct wrong knowledge. Supersedes the original entry, creates a corrected version, and propagates corrections to related conflicting entries.')] | ||
| class CorrectTool extends Tool | ||
| { | ||
| public function __construct( | ||
| private readonly CorrectionService $correctionService, | ||
| ) {} | ||
|
|
||
| public function handle(Request $request): Response | ||
| { | ||
| $id = $request->get('id'); | ||
| $correctedContent = $request->get('corrected_content'); | ||
|
|
||
| if (! is_string($id) || $id === '') { | ||
| return Response::error('Provide the ID of the entry to correct.'); | ||
| } | ||
|
Comment on lines
+26
to
+28
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Allow numeric IDs for correction requests. Line 26 currently rejects non-string IDs, but Suggested fix- if (! is_string($id) || $id === '') {
+ if ((! is_string($id) && ! is_int($id)) || (is_string($id) && $id === '')) {
return Response::error('Provide the ID of the entry to correct.');
}🤖 Prompt for AI Agents |
||
|
|
||
| if (! is_string($correctedContent) || strlen($correctedContent) < 10) { | ||
| return Response::error('Provide corrected content of at least 10 characters.'); | ||
| } | ||
|
|
||
| try { | ||
| $result = $this->correctionService->correct($id, $correctedContent); | ||
|
|
||
| return Response::text(json_encode([ | ||
| 'status' => 'corrected', | ||
| 'corrected_entry_id' => $result['corrected_entry_id'], | ||
| 'original_id' => $id, | ||
| 'superseded_ids' => $result['superseded_ids'], | ||
| 'conflicts_resolved' => $result['conflicts_found'], | ||
| 'message' => "Entry corrected. New entry: {$result['corrected_entry_id']}. " | ||
| .count($result['superseded_ids']).' related entries superseded.', | ||
| ], JSON_THROW_ON_ERROR)); | ||
| } catch (\RuntimeException $e) { | ||
| return Response::error('Correction failed: '.$e->getMessage()); | ||
| } | ||
| } | ||
|
|
||
| public function schema(JsonSchema $schema): array | ||
| { | ||
| return [ | ||
| 'id' => $schema->string() | ||
| ->description('ID of the entry to correct (from a previous recall result).') | ||
| ->required(), | ||
| 'corrected_content' => $schema->string() | ||
| ->description('The corrected information that replaces the wrong content.') | ||
| ->required(), | ||
| ]; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Validate categories and enforce positive bounds before
scroll()calls.Line 47 currently permits mixed arrays; those values are forwarded as category filters on Line 111. Also, Line 48/49 allow non-positive
max_tokens/limit.Suggested fix
Also applies to: 105-114
🤖 Prompt for AI Agents