Skip to content

Commit e21a81d

Browse files
committed
Enabled logging by default
1 parent 4614dc5 commit e21a81d

File tree

22 files changed

+235
-410
lines changed

22 files changed

+235
-410
lines changed

README.md

Lines changed: 0 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -229,31 +229,6 @@ $server = Server::builder()
229229
->build();
230230
```
231231

232-
### Logging
233-
234-
Automatically inject PSR-3 compatible logger into your registered handlers:
235-
236-
```php
237-
// Enable logging in server
238-
$server = Server::builder()
239-
->enableClientLogging()
240-
->build();
241-
242-
// Use in any handler - logger is auto-injected
243-
#[McpTool]
244-
public function processData(string $input, ClientLogger $logger): array {
245-
$logger->info('Processing data', ['input' => $input]);
246-
return ['result' => 'processed'];
247-
}
248-
249-
// Also works with PSR-3 LoggerInterface
250-
#[McpResource(uri: 'data://config')]
251-
public function getConfig(LoggerInterface $logger): array {
252-
$logger->info('Config accessed');
253-
return ['setting' => 'value'];
254-
}
255-
```
256-
257232
## Documentation
258233

259234
**Core Concepts:**

docs/mcp-elements.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ discovery and manual registration methods.
1111
- [Resources](#resources)
1212
- [Resource Templates](#resource-templates)
1313
- [Prompts](#prompts)
14+
- [Logging](#logging)
1415
- [Completion Providers](#completion-providers)
1516
- [Schema Generation and Validation](#schema-generation-and-validation)
1617
- [Discovery vs Manual Registration](#discovery-vs-manual-registration)
@@ -478,6 +479,55 @@ public function generatePrompt(string $topic, string $style): array
478479

479480
The SDK automatically validates that all messages have valid roles and converts the result into the appropriate MCP prompt message format.
480481

482+
## Logging
483+
484+
The SDK provides automatic logging support, handlers can receive logger instances automatically to send structured log messages to clients.
485+
486+
### Configuration
487+
488+
Logging is **enabled by default**. Use `disableClientLogging()` to turn it off:
489+
490+
```php
491+
// Logging enabled (default)
492+
$server = Server::builder()->build();
493+
494+
// Disable logging
495+
$server = Server::builder()
496+
->disableClientLogging()
497+
->build();
498+
```
499+
500+
### Auto-injection
501+
502+
The SDK automatically injects logger instances into handlers:
503+
504+
```php
505+
use Mcp\Capability\Logger\ClientLogger;
506+
use Psr\Log\LoggerInterface;
507+
508+
#[McpTool]
509+
public function processData(string $input, ClientLogger $logger): array {
510+
$logger->info('Processing started', ['input' => $input]);
511+
$logger->warning('Deprecated API used');
512+
513+
// ... processing logic ...
514+
515+
$logger->info('Processing completed');
516+
return ['result' => 'processed'];
517+
}
518+
519+
// Also works with PSR-3 LoggerInterface
520+
#[McpResource(uri: 'data://config')]
521+
public function getConfig(LoggerInterface $logger): array {
522+
$logger->info('Configuration accessed');
523+
return ['setting' => 'value'];
524+
}
525+
```
526+
527+
### Log Levels
528+
529+
The SDK supports all standard PSR-3 log levels with **warning** as the default level:
530+
481531
## Completion Providers
482532

483533
Completion providers help MCP clients offer auto-completion suggestions for Resource Templates and Prompts. Unlike Tools

docs/server-builder.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,7 @@ $server = Server::builder()
508508
| `addRequestHandlers()` | handlers | Prepend multiple custom request handlers |
509509
| `addNotificationHandler()` | handler | Prepend a single custom notification handler |
510510
| `addNotificationHandlers()` | handlers | Prepend multiple custom notification handlers |
511+
| `disableClientLogging()` | - | Disable MCP client logging (enabled by default) |
511512
| `addTool()` | handler, name?, description?, annotations?, inputSchema? | Register tool |
512513
| `addResource()` | handler, uri, name?, description?, mimeType?, size?, annotations? | Register resource |
513514
| `addResourceTemplate()` | handler, uriTemplate, name?, description?, mimeType?, annotations? | Register resource template |

examples/stdio-discovery-calculator/McpElements.php

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@ final class McpElements
3232

3333
public function __construct(
3434
private readonly LoggerInterface $logger = new NullLogger(),
35-
) {
36-
}
35+
) {}
3736

3837
/**
3938
* Performs a calculation based on the operation.
@@ -95,7 +94,7 @@ public function calculate(float $a, float $b, string $operation, ClientLogger $l
9594
}
9695

9796
$finalResult = round($result, $this->config['precision']);
98-
$logger->info('Calculation completed successfully', [
97+
$logger->info('Calculation completed successfully', [
9998
'result' => $finalResult,
10099
'precision' => $this->config['precision'],
101100
]);
@@ -164,7 +163,7 @@ public function updateSetting(string $setting, mixed $value, ClientLogger $logge
164163
return ['success' => false, 'error' => 'Invalid precision value. Must be integer between 0 and 10.'];
165164
}
166165
$this->config['precision'] = $value;
167-
$logger->info('Precision setting updated', [
166+
$logger->info('Precision setting updated', [
168167
'new_precision' => $value,
169168
'previous_config' => $this->config,
170169
]);
@@ -190,12 +189,12 @@ public function updateSetting(string $setting, mixed $value, ClientLogger $logge
190189
}
191190
}
192191
$this->config['allow_negative'] = $value;
193-
$logger->info('Allow negative setting updated', [
192+
$logger->info('Allow negative setting updated', [
194193
'new_allow_negative' => $value,
195194
'updated_config' => $this->config,
196195
]);
197196

198197
// $registry->notifyResourceChanged('config://calculator/settings');
199-
return ['success' => true, 'message' => 'Allow negative results set to '.($value ? 'true' : 'false').'.'];
198+
return ['success' => true, 'message' => 'Allow negative results set to ' . ($value ? 'true' : 'false') . '.'];
200199
}
201200
}

examples/stdio-discovery-calculator/server.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
* file that was distributed with this source code.
1111
*/
1212

13-
require_once dirname(__DIR__).'/bootstrap.php';
13+
require_once dirname(__DIR__) . '/bootstrap.php';
1414
chdir(__DIR__);
1515

1616
use Mcp\Server;
@@ -23,7 +23,6 @@
2323
->setInstructions('This server supports basic arithmetic operations: add, subtract, multiply, and divide. Send JSON-RPC requests to perform calculations.')
2424
->setContainer(container())
2525
->setLogger(logger())
26-
->enableClientLogging() // Enable Client logging capability and auto-injection!
2726
->setDiscovery(__DIR__, ['.'])
2827
->build();
2928

examples/stdio-logging-showcase/server.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
* file that was distributed with this source code.
1111
*/
1212

13-
require_once dirname(__DIR__).'/bootstrap.php';
13+
require_once dirname(__DIR__) . '/bootstrap.php';
1414
chdir(__DIR__);
1515

1616
use Mcp\Server;
@@ -23,7 +23,6 @@
2323
->setServerInfo('Stdio Logging Showcase', '1.0.0', 'Demonstration of auto-injected MCP logging in capability handlers.')
2424
->setContainer(container())
2525
->setLogger(logger())
26-
->enableClientLogging() // Enable MCP logging capability and auto-injection!
2726
->setDiscovery(__DIR__, ['.'])
2827
->build();
2928

src/Capability/Discovery/SchemaGenerator.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -806,7 +806,7 @@ private function isAutoInjectedParameter(\ReflectionParameter $parameter): bool
806806
$typeName = $type->getName();
807807

808808
// Auto-inject for ClientLogger or LoggerInterface types
809-
return 'Mcp\\Capability\\Logger\\ClientLogger' === $typeName
809+
return 'Mcp\\Capability\\Logger\\ClientLogger' === $typeName
810810
|| 'Psr\\Log\\LoggerInterface' === $typeName;
811811
}
812812
}

src/Capability/Registry.php

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,9 @@ final class Registry implements ReferenceProviderInterface, ReferenceRegistryInt
6666

6767
private ServerCapabilities $serverCapabilities;
6868

69-
private bool $loggingMessageNotificationEnabled = false;
69+
private bool $logging = true;
7070

71-
private ?LoggingLevel $currentLoggingMessageNotificationLevel = null;
71+
private LoggingLevel $loggingLevel = LoggingLevel::Warning;
7272

7373
public function __construct(
7474
private readonly ?EventDispatcherInterface $eventDispatcher = null,
@@ -77,21 +77,21 @@ public function __construct(
7777
}
7878

7979
/**
80-
* Enables logging message notifications for this registry.
80+
* Disable logging message notifications for this registry.
8181
*/
82-
public function enableLoggingMessageNotification(): void
82+
public function disableLogging(): void
8383
{
84-
$this->loggingMessageNotificationEnabled = true;
84+
$this->logging = false;
8585
}
8686

8787
/**
8888
* Checks if logging message notification capability is enabled.
8989
*
90-
* @return bool True if logging message notification capability is enabled, false otherwise
90+
* @return bool True if logging capability is enabled, false otherwise
9191
*/
92-
public function isLoggingMessageNotificationEnabled(): bool
92+
public function isLoggingEnabled(): bool
9393
{
94-
return $this->loggingMessageNotificationEnabled;
94+
return $this->logging;
9595
}
9696

9797
/**
@@ -100,19 +100,19 @@ public function isLoggingMessageNotificationEnabled(): bool
100100
* This determines which log messages should be sent to the client.
101101
* Only messages at this level and higher (more severe) will be sent.
102102
*/
103-
public function setLoggingMessageNotificationLevel(LoggingLevel $level): void
103+
public function setLoggingLevel(LoggingLevel $level): void
104104
{
105-
$this->currentLoggingMessageNotificationLevel = $level;
105+
$this->loggingLevel = $level;
106106
}
107107

108108
/**
109109
* Gets the current logging message notification level set by the client.
110110
*
111-
* @return LoggingLevel|null The current log level, or null if not set
111+
* @return LoggingLevel The current log level
112112
*/
113-
public function getLoggingMessageNotificationLevel(): ?LoggingLevel
113+
public function getLoggingLevel(): LoggingLevel
114114
{
115-
return $this->currentLoggingMessageNotificationLevel;
115+
return $this->loggingLevel;
116116
}
117117

118118
public function getCapabilities(): ServerCapabilities
@@ -129,7 +129,7 @@ public function getCapabilities(): ServerCapabilities
129129
resourcesListChanged: $this->eventDispatcher instanceof EventDispatcherInterface,
130130
prompts: [] !== $this->prompts,
131131
promptsListChanged: $this->eventDispatcher instanceof EventDispatcherInterface,
132-
logging: $this->loggingMessageNotificationEnabled,
132+
logging: $this->logging,
133133
completions: true,
134134
);
135135
}

src/Capability/Registry/ReferenceProviderInterface.php

Lines changed: 0 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111

1212
namespace Mcp\Capability\Registry;
1313

14-
use Mcp\Schema\Enum\LoggingLevel;
1514
use Mcp\Schema\Page;
1615

1716
/**
@@ -66,34 +65,4 @@ public function getResourceTemplates(?int $limit = null, ?string $cursor = null)
6665
* Checks if any elements (manual or discovered) are currently registered.
6766
*/
6867
public function hasElements(): bool;
69-
70-
/**
71-
* Enables logging message notifications for the MCP server.
72-
*
73-
* When enabled, the server will advertise logging capability to clients,
74-
* indicating that it can emit structured log messages according to the MCP specification.
75-
*/
76-
public function enableLoggingMessageNotification(): void;
77-
78-
/**
79-
* Checks if logging message notification capability is enabled.
80-
*
81-
* @return bool True if logging message notification capability is enabled, false otherwise
82-
*/
83-
public function isLoggingMessageNotificationEnabled(): bool;
84-
85-
/**
86-
* Sets the current logging message notification level for the client.
87-
*
88-
* This determines which log messages should be sent to the client.
89-
* Only messages at this level and higher (more severe) will be sent.
90-
*/
91-
public function setLoggingMessageNotificationLevel(LoggingLevel $level): void;
92-
93-
/**
94-
* Gets the current logging message notification level set by the client.
95-
*
96-
* @return LoggingLevel|null The current log level, or null if not set
97-
*/
98-
public function getLoggingMessageNotificationLevel(): ?LoggingLevel;
9968
}

src/Capability/Registry/ReferenceRegistryInterface.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
namespace Mcp\Capability\Registry;
1313

1414
use Mcp\Capability\Discovery\DiscoveryState;
15+
use Mcp\Schema\Enum\LoggingLevel;
1516
use Mcp\Schema\Prompt;
1617
use Mcp\Schema\Resource;
1718
use Mcp\Schema\ResourceTemplate;
@@ -88,4 +89,31 @@ public function getDiscoveryState(): DiscoveryState;
8889
* Manual elements are preserved.
8990
*/
9091
public function setDiscoveryState(DiscoveryState $state): void;
92+
93+
/**
94+
* Disables logging for the server.
95+
*/
96+
public function disableLogging(): void;
97+
98+
/**
99+
* Checks if logging capability is enabled.
100+
*
101+
* @return bool True if logging capability is enabled, false otherwise
102+
*/
103+
public function isLoggingEnabled(): bool;
104+
105+
/**
106+
* Sets the current logging level for the client.
107+
*
108+
* This determines which log messages should be sent to the client.
109+
* Only messages at this level and higher (more severe) will be sent.
110+
*/
111+
public function setLoggingLevel(LoggingLevel $level): void;
112+
113+
/**
114+
* Gets the current logging level set by the client.
115+
*
116+
* @return LoggingLevel The current log level
117+
*/
118+
public function getLoggingLevel(): LoggingLevel;
91119
}

0 commit comments

Comments
 (0)